Static Events

Published 1/7/2013 by Christian in Code

Using Static Events should be done with care, if you are subscribing to such an event from instances, as a race condition could occur, when subscribing and null-checking the event.
The trick here is to subscribe a trivial handler to the static event, when declaring it, eg.:

//Added a trivial handler to avoid race condition;
public static event EventHandler DataChangedEvent = delegate { };

Then you can use it without the null check.

//No need to null check. A trivial event handler has been subscribed to event.
DataChangedEvent(ToolTip, EventArgs.Empty);

Oh by the way - this trick naturally also applies to instance events.

As always, feel free to comment, or ask.

 

Edit

In C# 6.0 this can actually be done much more nicely, using the 'Null-conditional operators'.

 

DataChangedEvent?.Invoke(ToolTip, EventArgs.Empty);

 

This way you don't need to subscribe the trivial handler to the static event. So declaring it will just look like this - even for a static event:

public static event EventHandler DataChangedEvent;

You can watch Mads Torgersen brief video on C# 6.0 here:

http://channel9.msdn.com/Events/Visual-Studio/Connect-event-2014/116


Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading