Wednesday, September 24, 2008

C# : events

Custom eventargs do not need to to use a new custom delegate, you can simply say

public event EventHandler<myEventArgs> NewData;

Why is sender of type object??

  1. if you inherit the event, you would still need to cast to the derived class, so might as well cast from object.
  2. delegate can be used by other types too.

all eventhandlers have return type as void, since there is no way to get the return values from all of the function registered.

The method to raise the event should be - protected virtual.

Use a temp variable to ensure type safety. i.e.

EventHandler<NewMailEventArgs> temp = NewMail;

if(temp !=null) temp(this,e);

You have System.Reflection.EventInfo

As long as an object has registered one of its methods with an event, the object cant be GCed, so unregister events in Dispose().

Registration or un-registration - only one should be executed at a time, so they are marked with [MethodImpl(MethodImplOptions.Synchronized)]. When MethodImpl attribute is applied to an instance method, the CLR uses the object itself as the thread-sync lock, this means that if a class is defines many events, all reg/un-reg methods use the same lock and this hurts scalability, if you have multiple threads reg/un-reg on different events simultaneously.

Thread-synchronization guidelines state that methods should not take a lock on the object itself because the lock is exposed publicly to any and all code. This means that anyone could write code that locks the object, potentially causing other threads to deadlock.

for robust implementation - explicitly control event reg/un-reg

value types can have events - no synchronization.

No comments: