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);
}

Leave a Comment


NOTE - You can 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>