Why refer to an event through a variable?

I continue to see this pattern of triggering events in other people's code:

void OnMyEvent() { var myEvent = MyEvent; if (myEvent != null) myEvent(this, EventArgs.Empty); } 

What is the advantage of using a variable to refer to the MyEvent event, rather than using MyEvent(this, EventArgs.Empty) ?

+4
source share
1 answer

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) // 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 } } 
+8
source

Source: https://habr.com/ru/post/1434149/


All Articles