Nexus's Threadpool

There is not one, there are many ...

September 2008 - Posts

Event Raising the good, the bad and the ugly ...

So you need to raise an event, and wanna do it in a threadsafe way, or safer way :)

Not so long ago i wrote this code :

...
public event EventHandler Save;
...
private void OnSave(EventArgs e)
{
if(Save != null) Save(this,EventArgs.Empty);
}


What is wrong here, the fact that the point between the not null check and the eventual event raising can has changes in between.

So from now just write this :

private void OnSave(EventArgs e)
{
EventHandler handlers = Save;
if (handlers != null) handlers(this, e);
}

This makes a copy into the handlers variable and cannot change between check and raise.

Posted: Sep 15 2008, 04:14 AM by Nexus | with no comments
Filed under: , ,