5

I noticed that quite a lot of code is using following code snippet to invoke event handler.

Public event EventHandler Handler;

Protected void OnEvent(){
      var handler = this.Handler;
      If(null!=handler){
          handler(this, new EventArgs());
      }
}

Why does it assign Handler to a local variable before invoking other than invoking the event on Handler directly. Is there any difference between those?

Colin
  • 551
  • 2
  • 10
  • 1
    Would [this previous post](http://stackoverflow.com/questions/12279901/var-handler-myevent-in-vb-net) also apply to your question? – Igor Feb 15 '16 at 16:22
  • 1
    I suggest you take a look at this Eric Lipert's article on MSDN https://blogs.msdn.microsoft.com/ericlippert/2009/04/29/events-and-races/ – Rodrigo Vedovato Feb 15 '16 at 16:22
  • 2
    Try this thread. Google is invaluable for these things. http://stackoverflow.com/questions/5147397/why-assign-a-handler-to-an-event-before-calling-it – DV8DUG Feb 15 '16 at 16:24
  • http://stackoverflow.com/questions/786383/c-sharp-events-and-thread-safety this is better reference – mybirthname Feb 15 '16 at 16:28

1 Answers1

3

This is a typical way to avoid a race condition.

When you're on a pre-emptively multi-tasked system, or worse, a multi-core system, a lot can happen between the if (Handler != null) check and the actual Handler(this, EventArgs.Empty);. Most importantly, it's perfectly possible that Handler wasn't null during the check, but is during the invocation itself - and now you've got a really hard to track NullReferenceException.

In contrast, by storing the Handler to a local variable, you ensure no other thread is going to mess with it while you are doing your check and invoke.

Note that this still leaves you open to other kinds of race conditions :)

Luaan
  • 62,244
  • 7
  • 97
  • 116