Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why reference an event through a variable?

I keep seeing this pattern of invoking events in other people's code:

void OnMyEvent()
{
  var myEvent = MyEvent;

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

What is the benefit of using a variable in order to reference the event MyEvent, rather than directly using MyEvent(this, EventArgs.Empty)?

like image 263
waldrumpus Avatar asked Feb 20 '23 03:02

waldrumpus


1 Answers

In a multi threaded application, the event may get unsubscribed from in the middle of the call on this method.

This can cause a NullReferenceException if the event handler is not copied in this manner.

void OnMyEvent()
{
  if (MyEvent!= null)                // Thread A checks event 
  {                                  // Thread B unsubscribes _last_ handler 
    MyEvent(this, EventArgs.Empty);  // Boom!
  }
}

But with:

void OnMyEvent()
{
  var myEvent = MyEvent;             // Thread A gets _copy_ of invocation list
  if (myEvent != null)               // Using copy, so no problem 
  {                                  // Thread B unsubscribes _last_ handler
    myEvent(this, EventArgs.Empty);  // Still using copy, so no problem 
  }
}
like image 90
Oded Avatar answered Feb 27 '23 10:02

Oded