Some days ago, I encountered a problem with an event being not-null when checked, but null when called:
if (MyEvent != null)
MyEvent();
Since this is flawed code (MyEvent may be unregistered by another thread between checking and calling, thereby triggering a NullReferenceException), I changed the code following the recommendations:
var handler = MyEvent;
if (handler != null)
handler();
But mysteriously, the problem still exists. Sometimes I get a NullReferenceException. The debugger shows that MyEvent is null, but handler is not. How can handler possibly still throw a NullReferenceException? I thought this is threadsafe code, what am I missing?
Update
As I now learned from this blogpost: https://blogs.msdn.microsoft.com/ericlippert/2009/04/29/events-and-races/ the pattern is not really thread-safe. It seems as if registering events when at the same time firing them can lead to strange behavior.
On second thought, this seems not implausible. Since an event is in principle just a list of methods to be executed, reading from and writing to the list at the same time may very well pose serious problems. This is well known from Collections (that's why ObservableCollections exist), so it seems fair to assume that the same problems can happen when operating on events.
I'm going to dig deeper to find out more.