为什么调用前处理函数分配给一个事件? [英] 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"?
推荐答案
分配给本地变量保证,如果事件被在<$之间注销C $ C>如果和实际调用,调用列表将不为空(因为变量都会有一个的复制的原调用列表)。
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).
这可以很容易地发生在多线程代码,其中间检查空和发射可能被另一个线程注销该事件。
This can easily happen in multithreaded code, where between checking for a null and firing the event it may be unregistered by another thread.
请参阅这个,以便问题和答案。
See this SO question and answers.
这篇关于为什么调用前处理函数分配给一个事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!