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?
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With