You can use the setter property to raise an event whenever the field value is changed.
You can have your own EventHandler delegate or you can use the famous System.EventHandler delegate.
Usually there is a template for this:
- Define a public event with an event handler delegate (which has an argument of type EventArgs).
- Define the OnXXXXX protected virtual method (e.g. OnMyPropertyValueChanged). In this method, you must check whether the delegation of the event handler is zero, and if you do not call it (this means that one or more methods are attached to the delegation of events).
- Call this protected method when you want to notify subscribers that something has changed.
Here is an example
private int _age;
The advantage of this approach is that you allow any other classes that want to inherit from your class to change behavior if necessary.
If you want to catch an event in another thread that it raises, you must be careful not to change the state of objects that are defined in another thread, which will cause a cross-thread exception. To avoid this, you can either use the Invoke method for the object for which you want to change its state, to make sure that this change occurs in the same stream that the event was raised, or if you are dealing with Windows Form, can use BackgourndWorker to make something in a parallel stream beautiful and light.
Beatles1692 Apr 30 '11 at 15:00 2011-04-30 15:00
source share