Usage of DataRow.BeginEdit() and DataRow.EndEdit() for single change - c#

I have quite a lot of code in the following form:
// assume that MyDataRow is a datarow from a typed dataset and has a property called SomeInt
MyDataRow row;
row.BeginEdit();
row.SomeInt = 42;
row.EndEdit();
The documentation of DataRow.BeginEdit states the following:
Use the BeginEdit method to put a DataRow into edit mode. In this
mode, events are temporarily suspended, letting the user make changes
to more than one row without triggering validation rules.
So, in the given case, when there is only one change, the usage of the BeginEdit- and EndEdit-methods is not needed at all, or am I missing something? I.e. is it safe to just get rid of these calls, or is it good practice to keep them?

If you are working by binding data to control, then use BeginEdit() and EndEdit() always. There may be events or triggers on your project, and if you will not use BeginEdit() and EndEdit() your assigned value may change in any event or trigger, and it will take a lot of time to find bug.

Related

Does .NET CLR precalculate property values?

When I run C# code through the debugger, calculated property values always seem to be displayed when I inspect an object.
e.g.
I am wondering if this is only done in the debugger, or if .Net does this as an optimization and can detect when a property changes, because this would affect how I use and access such properties to avoid performing calculations multiple times.
I have never seen it not display the value in the debugger even with complex calculations.
The debugger is calling .ToString() on all the objects. Whatever code is implemented in that function for each object is executed, which may mean it looks like the debugger has some insider information, but it really doesn't.
You can confirm this by writing your own .ToString() function in a class and see what happens.
The value of your auto-property will be computed when something calls the getter. It just so happens that the debugger will call the getter to display the property value, which is what you are seeing.
I am wondering if ... .Net does this as an optimization and can detect when a property changes, because this would affect how I use and access such properties to avoid performing calculations multiple times.
There is no built-in property value caching. Since the get method will be executed whenever you "get" the property, the calculation will be executed every time. If you want to cache the value, you could add a backing field, but you'll need to detect if/when to recalculate the value. One way would be to add logic to the setter of Value to either invalidate the cache or recompute the dependent properties (like MessageCode) at that time.
My opinion is that such a simple calculation is safe to run millions of times rather then adding the overhead of change detection.

Call methods from set accessor or force the user to do manually

When a property is updated is it good practice to change other properties based on this or should you force the user to call a method directly? For example:
someObject.TodaysTotalSales = 1234.56;
Would it be OK to have the set accessor update another value say ThisYearsTotalSales or should you force the end user to do it manually.
someObject.TodaysTotalSales = 1234.56;
someObject.UpdateThisYearsTotal();
I think the best practise is to recalculate the total year consumption only when it is accessed. Otherwise if you update the TodaysTotalSales property very often, you will compute the total year count for nothing.
More generally, when you call a property setter, you don't expect a complex operation. By convention, getters and setters are expected to return almost immediately.
If your algorithm is too complex, in that case you can use a cache value to avoid a recalculation at each call; you invalidate the cache value when one of its prerequisite has changed
It depends.
Does he need to know the TotalYearsOfSales even after he updated TodaysSales?
Yes -> Provide an additional method to update someObject.UpdateThisYearsTotal(); and at the same time flag that he has not updated YearsTotal while he did update TodaysSales, so you can throw some error at the end of the process if needed
No -> Autoupdate other properties of which the values are not needed to prior to updating the TodaysSales
TL;DR: it depends
I assume you have public interface of a class in mind.
If you follow OOP Encapsulation principle to the limit, then someObject's externally visible state should be consistent with every public access, i.e. you shouldn't need any public UpdateState methods. So in this case someObject.UpdateThisYearsTotal() is a no-no. What happens internally: be it lazy recalculation, caching, private UpdateAllInternal - would not matter.
But OOP is not an icon/idol - so for performance reasons you may design program flow as you see fit. For example: deferred bulk data processing, game loop, Entity Component System design, ORMs - those systems clearly state in their docs (rarely in code contracts) the way they are supposed to be used.

Object Reset method or new reference for event subscribers?

(Using VS2010. Assume performance is not an issue).
I have a particular object that implements events for all its property changes. Sometimes it will be necessary to "reset" the object to all its default property values. The easiest way to do this is simply construct a new object:
Object1= New MyObject
However, for any event subscribers to the original object, this is equivalent to a change of all property values. For example, if a subscriber was listening only for updates to property A, now it must also be aware of the possibility of new object construction. This seems to add extra effort for subscribers. (For example, maybe I would have to create a "NewObjectAssigned" event, and subscribers to property changes would need to handle that as well.)
So instead I was thinking of outfitting the object with a Reset method, so the above code changes to:
Object1.Reset
That way the Object1 reference never changes, and the Reset would manually change all properties to default values, thereby triggering all propertychanged events. But this also doesn't feel quite right, and cumbersome compared to just declaring a new object. I guess it irks me to need a method that either manually resets all properties or raises all changed events - I'd have to remember to update this method whenever new properties are added to the class. Or perhaps this isn't as problematic as I'm making it out to be.
This is a simple enough scenario that I'm sure there is a best practices for this, one way or another. Which is preferable?
If you need your event handlers to stay attached, then you'll want to use a reset instead of creating a new instance. If your object implements INotifyPropertyChanged, then you can send a single event for the reset with PropertyName set to null.
From MSDN:
An Empty value or null for the propertyName parameter indicates that all of the properties have changed.
I think I agree with Peter Ritchie's first comment, that my original question was lacking in details necessary to determine a "preferable" method. As it stands, I'm probably going with his suggestion of a wrapper class, that will be responsible for handling new object references and exposing events to subscribers.

How to decide between a method or event?

I read a question ages ago "How do C# Events work behind the scenes?" and Jon answered that all events are similar to methods...
In a purely hypothetical situation, I was wondering if someone could explain or point me to a resource that says when to use an event over a method?
Basically, If I want to have a big red/green status picture which is linked to a Bool field, and I wanted to change it based on the value of the bool, should I:
a) Have a method called Changepicture which is linked to the field and changes the state of the bool and the picture.
b) Have a get/set part to the field and stick an event in the set part.
c) Have a get/set part to the field and stick a method in the set part.
d) Other?
To gain more information about events see this post.
You have options.
If your object already implements INotifyPropertyChanged and your red/green picture is a control which supports databinding, then you can simply fire the NotifyPropertyCHanged event on the bool's set method, and add a databinding on that property to your control.
If not implementing INotifyPropertyChanged, I would still recommend doing something similar. I.e. creating your own event handler, and having the reg/green picture subscribe to the event. Just straight up calling a method from the set of your property creates a tight coupling, which is generally a bad thing to do.
The answer is: It depends.
If your boolean value is in the codebehind class of your visual component (e.g. WinForm) you can call a method ChangePicture without doing strange things. But if your boolean value is architectural more far away from the visual component an event is the right way to handle the scenario because you can not easily call a method on the visual component because the class that contains the boolean value perhaps doesn´t even know your visual component exists. :)
The best way to figure out what you should do is to look at classes in the .NET framework and see how they are designed.
Methods are "doers" or "actions", while you can see events as notification mechanisms. That is if others could be interested is being notified when something happens in an object then you can surface an event and have one or more subscribers to these events.
Since events in .NET are multi-cast, meaning multiple objects can subscribe and therefore be notified of an event happening, that may be other reason to raise an event in your objects. Events also follow the observer pattern in that the subject (your class) is really unaware of the subscribers (loosely coupled). While in order to call a method, the secondary object needs to have a reference to an instance of your class.
Note that, a method in your class eventually raises and event. So let's say you have a method in your class called ChangePicture. Then in the method's implementation, you could eventually raise an event PictureChanged. if someone is interested in being notified of this event, they can subscribe to this event. This someone is typically not the one that made the method call to change the picture.
Events are delegates. Delegates are objects. Event's are actually MulticastDelegates (a base class in the .NET framework). These objects eventually call a method, which is the method that gets called as part of the event notification. So they are slightly "heavier" then just a method call, but that should almost never determine your design.

Thread safety advice when using DataGridView and BindingList in C#

I'm writing a class for logging events. My LogClass is implemented as a singleton, and any class in the system can write a log entry. The entries are stored in a List and when a buffer is filled they get dumped to the disk.
I'm using a DataGridView to display the contents of the LogClass during execution, therefore I used the BindingList so that the Viewer would update automatically.
I'm wondering how thread safe my class is.
I'm using "lock" everytime I add a new entry to the list, and when I'm iterating through the list to dump it to the disk.
Besides the DataGridView, the class is basically Write-Only because there isn't an option to read from the log, only to add entrires to the log.
The dump is executed internally, and that is the only time there is a explicit read command on the BindingList.
So my real concern is what goes on with the DataGridView and the BindingList ?
The BindingList throws an event everytime the list changes.
This doesnt seem like a concern when adding new entries, because the event is thrown when the adding finished.
My code for Dump() is:
lock (lockObj) {
foreach (LogEntry le in List) {
writeToDisk(le)
removeFromList(le)
}
}
Even though I'm locking the list during the whole iteration, an event is thrown to the Viewer that the list changed (because of the removal) and therefore being read by the DataGridView. I don't really want anything reading/writing to the list while I'm altering it.
Any ideas?
It's not really a concern because, once bound, you can only change the list from the Form.Invoke method (inherited from Control.Invoke). If you try to change the list from another thread, the .NET runtime will bark at your w/ an exception saying something to the effect of "can't change this list from current thread".
This has some code you can grab.
Regards,
=Alan
I thought that BindingList didn't implement change notification. In this scenario I don't think this is thread safe.
The solution might be to use custom collection that implements IBindingList and change the list accessor to acquire lock before returning any element.
I have a custom implementation of IBindingList with change notification so if you want I can share this.(I'll probably write an article on code project describing the implementation anyway..)

Categories