关于事件的价值/参考类型的问题 [英] Question regarding to value/reference type of events

查看:18
本文介绍了关于事件的价值/参考类型的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 MSDN 上,我发现了以下内容:

On the MSDN, I have found following:

public event EventHandler<MyEventArgs> SampleEvent;

public void DemoEvent(string val)
{
// Copy to a temporary variable to be thread-safe.
    EventHandler<MyEventArgs> temp = SampleEvent; 

是参考吗?
如果是这样,当 SampleEvent 变为 null 时,我不明白它的含义,那么 temp 也是如此

Is it reference?
If so I do not understand its meaning as when SampleEvent became null, so does the temp

    if (temp != null)
        temp(this, new MyEventArgs(val));
}

推荐答案

这是与线程有关的偏执狂.如果另一个线程取消订阅最后一个处理程序就在你检查了它的null之后,它可能变成 null 会导致异常.由于委托是不可变的,因此将委托的快照捕获到变量中可以防止这种情况发生.

This is a paranoia thing to do with threading. If another thread unsubscribes the last handler just after you've checked it for null, it could become null and you'll cause an exception. Since delegates are immutable, capturing a snapshot of the delegate into a variable stops this from happening.

当然,它确实有 other 副作用,您可以(相反)最终针对认为它已经取消订阅的对象引发事件......

Of course, it does have the other side effect that you could (instead) end up raising the event against an object that thinks it already unsubscribed...

但要强调的是 - 这只是在多个线程订阅/取消订阅对象时才会出现的问题,这是 a:很少见,b:不是完全可取的.

But to stress - this is only an issue when multiple threads are subscribing / unsubscribing to the object, which is a: rare, and b: not exactly desirable.

这篇关于关于事件的价值/参考类型的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆