Thread-safe event raising

Normally you would write this to make a temporary copy of your event in case something happend with SomeEvent:

EventHandler tmp = SomeEvent;

if (tmp != null) tmp(this, EventArgs.Empty);

Well you might consider this code below according to Jeffrey Richter his CLR via C# book.
The code above can cause some trouble because a compiler might optimize this code and remove the temporary copy of your event (depends on the implementation of the compiler).


EventHandler tmp = Interlocked.CompareExchange(ref SomeEvent, null, null);

if (tmp != null) tmp(this, e);

[ source ]

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s