Custom Event Handlers






1.27/5 (5 votes)
Apr 11, 2007
1 min read

26280

209
Improved custom implementation of event handling mechanism in c#
Introduction
I found it useful to use custom EventHandlers instead of framework's EventHandler and EventHandler<T> delegates.
- Often I had a mistake of multiple assigns of same method to delegate what caused problems.
- Calling UI thread from different thread is forbidden and problematic in framework and I found on internet nice solution that should be part of Event class for consistency.
- I'd like to have nicer event calling mechanism without checking for null .
Solution : class Event.cs .
- Uses standard framework delegates EventHandler and EventHandler<T> so it can be easy used in interfaces interchangeable with standard events.
- Exception when duplicate method assign.
- Automatic using of ISynchronizeInvoke when calling UI thread.
- Uses standard framework EventArgs ;
- Serialization support (no attributes to bypass serialization needed)
- Event class contains also static methods for firing EventHandlers with support of ISynchronizeInvoke for UI firing from different thread. Syntax: Event.Fire(...); Event.SafeFire(...);
Using the code
-Event myEvent = new Event() (uses EventHandler
internally) or Event<T> myEvent = new Event<T>() (uses
EventHandler<T>)
-assigning via standard += -=
-myEvent.Fire(senderObject) , myEvent.Fire(args,senderObject) and for safe UI firing support myEvent.SafeFire(...
- for usage in interfaces use in class:
public event EventHandler MyEvent { add { myEvent+= value; } remove { myEvent -= value; } } and in interface then standard : event EventHandler MyEvent;
History
9 May 2007 - Initial release on Code Project.