C#: Thread Safe Event calls

Sudhanshu's Ode to Code

Hello World,

While working on a multi-threaded Windows service that used events heavily, I did some research on how to trigger events in a thread safe manner. Inevitably, one looks for reference material or books that have the respect of the community and Jeffery Richter’s CLR via C# is one such resource.

The Context

In the chapter on Events (Chapter 11, pg 265 in the eBook), Jeffery summarizes the first 3 steps of how to raise events in a thread safe manner by providing a snippet for an extension method that can do this as such:

The above code is supposed to be an improvement over the following way where one uses a temp variable to store the passed in delegate instance and then compares the temp to null:

The reason why he proposes the code in the extension method over the simpler approach above is that though in theory…

View original post 262 more words

Blog at WordPress.com.

Up ↑