Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign EventHandler to a local variable before invoking [duplicate]

Tags:

c#

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?

like image 833
Colin Avatar asked Oct 19 '22 15:10

Colin


1 Answers

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 :)

like image 156
Luaan Avatar answered Oct 29 '22 20:10

Luaan