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)
?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With