0

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.

Thern
  • 887
  • 5
  • 16
  • provide minimal example which will reproduce the problem. – mybirthname Dec 12 '16 at 13:06
  • @mybirthname: I can't. That's the problem. I tried to create a short sample that would reproduce it, but it wasn't possible up to now. And I would assume that if I was able to do that, I would also know the answer for the problem. – Thern Dec 12 '16 at 13:13
  • *How can handler possibly still throw a NullReferenceException?* Inside the method there probably is a problem. See the duplicate how to diagnose that. – Patrick Hofman Dec 12 '16 at 13:16
  • @PatrickHofman: handler() is an event. And the link says that the exception is thrown at the point of the event call "if no event handlers have been attached". But an event IS attached, since handler is not null. In fact, if it would not be attached, handler() would not be called because handler != null would yield false. – Thern Dec 12 '16 at 13:22

0 Answers0