问题描述
在 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.
这篇关于关于事件的价值/参考类型的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)