In a multi-threaded application, an event can be unsubscribed from the middle of a call to this method.
This can result in a NullReferenceException if the event handler is not copied in this way.
void OnMyEvent() { if (MyEvent!= null)
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 } }
source share