Assign EventHandler to a local variable before calling

I noticed that quite a lot of code uses the following code snippet to call an event handler.

Public event EventHandler Handler;

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

Why does it assign a Handlerlocal variable before the call, except to directly call the event on Handler. Is there a difference between the two?

+4
source share
1 answer

This is a typical way to avoid a race condition.

, , , if (Handler != null) Handler(this, EventArgs.Empty);. , , Handler null , , NullReferenceException.

, Handler , , , .

, :)

+2

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


All Articles