Why define an event reference before calling a call?

I found an example of a simple event dispatch. I do not understand the lineEventHandler<string> handler = MyEvent;

Why do they need to define a link to the event, and not just use it myEventto call?

The code

    public event EventHandler<string> MyEvent;  

    protected void SendEvent(string e)
    {
        EventHandler<string> handler = MyEvent;
        if (handler != null)
        {
            handler(this, e);
        }
    }
+4
source share
3 answers

I found the answer here .

In a multi-threaded environment, a client can unsubscribe from an event after checking for zero, but before the actual call and MyEvent are empty in this case.

+3
source
if (MyEvent!= null)
{
     // If MyEvent is set to NULL (unsubscribed) in another thread 
     // between these two lines, the program crashes.
     MyEvent(this, e);
}

EventHandler<string> handler = MyEvent;
if (handler != null)
{
    // GC cannot connect MyEvent because there is additional reference to it - handler.
    // handler is local and cannot be set to NULL from another thread.
    // The code is thread safe.
    handler(this, e);
}
+1
source

. , , .

+1

All Articles