为什么在调用事件之前为其分配处理程序? [英] Why assign a handler to an event before calling it?
问题描述
基本上,我已经看到这一切经常使用:
Basically, I've seen this used all to often:
public event MyEventHandler MyEvent;
private void SomeFunction()
{
MyEventHandler handler = this.MyEvent;
if (handler != null)
{
handler(this, new MyEventArgs());
}
}
它可以像这样轻松完成:
When it could just as easily be done like so:
public event MyEventHandler MyEvent;
private void SomeFunction()
{
if (MyEvent != null)
{
MyEvent(this, new MyEventArgs());
}
}
那么,我错过了什么?有没有人将事件分配给处理程序,然后提出处理程序而不是事件本身?只是最佳实践?
So, am I missing something? Is there some reason people assign the event to a handler, then raise the handler instead of the event itself? Is it just "best practice"?
推荐答案
对局部变量的赋值确保如果事件在如果
和实际调用,则调用列表不会为空(因为变量将具有原始调用列表的复制)。
The assignment to a local variable ensures that if the event gets unregistered between the if
and the actual invocation, the invocation list will not be null (since the variable will have a copy of the original invocation list).
这可以很容易地发生在多线程代码中,其中检查null并触发可能被另一个线程注销的事件。
This can easily happen in multithreaded code, where between checking for a null and firing the event it may be unregistered by another thread.
请参阅此问题和答案。
这篇关于为什么在调用事件之前为其分配处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!