4

I found some example of simple event sending. I don't understand the line EventHandler<string> handler = MyEvent;

Why they need to define a reference to the event and not just use the myEvent to make the invoke?

The code

    public event EventHandler<string> MyEvent;  

    protected void SendEvent(string e)
    {
        EventHandler<string> handler = MyEvent;
        if (handler != null)
        {
            handler(this, e);
        }
    }
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Yanshof
  • 9,659
  • 21
  • 95
  • 195

3 Answers3

3

I found the answer here.

In multithreaded environment it is possible for client do unsubscribe from event after check for null, but before the actual invocation and MyEvent in that case will be null.

Andrii Litvinov
  • 12,402
  • 3
  • 52
  • 59
1
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);
}
Alex F
  • 42,307
  • 41
  • 144
  • 212
  • but there is a listener to the event => that mean that someone have reference to the MyEvent already ( MyEvent != null ) => GC will not collect it – Yanshof Jul 23 '14 at 04:55
  • 1
    Consider the following line ececuted in another thread between test for null and invocation: `yourClass.MyEvent -= MyEventHandler;` If this handler is the last event handler for this event, this sets `MyEvent` to NULL. – Alex F Jul 23 '14 at 05:00
1

The reason is to due to thread safety. Between the null check and invocation, an event handler can be unsubscribed from on another thread, leaving you with a null value if you don't make that assignment.

Selali Adobor
  • 2,060
  • 18
  • 30
  • 1
    I can't add comments to questions, but I found that it was already asked on SO http://stackoverflow.com/questions/5147397/why-assign-a-handler-to-an-event-before-calling-it – Selali Adobor Jul 23 '14 at 05:06