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
NullReferenceExceptionif the event handler is not copied in this manner.But with: