About raising events

Very often i see people write the following to ‘safely’ raise a method:

public event EventHandler Stopped;

void RaiseStoppedEvent()
{
 if (Stopped != null) Stopped(this, EventArgs.Empty);
}

Some developers think that they should program defensively and avoid the potential concurrency problem:

public event EventHandler Stopped;

void RaiseStoppedEvent()
{
 var handler = Stopped;
 if (handler!= null) handler(this, EventArgs.Empty);
}

And then there is Tim’s way to raise an event: (If i’m not mistaken it was Ayende who once blogged about this)

public event EventHandler Stopped = delegate { };

void RaiseStoppedEvent()
{
 Stopped(this, EventArgs.Empty);
}

This entry was posted on Saturday, January 9th, 2010 at 18:42 and is filed under C#. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply