简体   繁体   English

为什么在调用之前为事件分配处理程序?

[英]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). 对局部变量的赋值可确保如果事件在if和实际调用之间取消注册,则调用列表将不为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. 这在多线程代码中很容易发生,在检查null和触发事件之间,它可能会被另一个线程取消注册。

See this SO question and answers. 看到这个问题和答案。

Thread safety. 线程安全。

What happens if between the time you check if MyEvent is null and you fire MyEvent, another thread comes along and unsubscribes from the event? 如果在您检查MyEvent是否为空并且触发MyEvent之间,另一个线程出现并取消订阅该事件会发生什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM