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 in C#. Bookmark the permalink.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>