It is not possible to fire an event in C# that has no handlers attached to it. So before each call it is necessary to check if the event is null.
if ( MyEvent != null ) {
MyEvent( param1, param2 );
}
I would like to keep my code as clean as possible and get rid of those null checks. I don't think it will affect performance very much, at least not in my case.
MyEvent( param1, param2 );
Right now I solve this by adding an empty inline handler to each event manually. This is error prone, since I need to remember to do that etc.
void Initialize() {
MyEvent += new MyEvent( (p1,p2) => { } );
}
Is there a way to generate empty handlers for all events of a given class automatically using reflection and some CLR magic?
The notation:
is not thread safe. You should do it this way:
I understand, that this is a bother, so you can do helper method:
and then call:
If you are using C# 3.0, you can declare helper method as extension method:
and then call:
Also you can create next extension/helper methods for other event handlers. For example:
You can write is as:
I am not sure what you want to do is correct.
You don't need several extension methods for different event handlers, you just need one:
C# event declarations unfortunately include a number of well-known safety problems and inefficiencies. I designed a number of extension methods on delegates to invoke them safely, and to register/unregister delegates in a thread-safe manner.
Your old event-raising code:
Your new code:
Your old event registration code:
Your new code:
No locking needed, no compiler-inserted dummy objects used to lock the events.
You can use PostSharp to on build time add this magic. It is the best way.
I saw this on another post and have shamelessly stolen it and used it in much of my code ever since:
* If anyone knows the origin of this technique, please post it in the comments. I really do believe in the source getting due credit.(Edit: I got it from this post Hidden Features of C#?)