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

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

问题描述

在MSDN,我发现以下内容:

 公共事件的EventHandler< MyEventArgs> SampleEvent; 

公共无效DemoEvent(字符串VAL)
{
//复制到一个临时变量是线程安全的。
&事件处理LT; MyEventArgs> TEMP = SampleEvent;



它是引用吗?结果
如果是这样,我不知道它何时意义SampleEvent成了空,所以没有温度

 如果(温度!= NULL)
温度(这一点,新MyEventArgs( VAL));
}


解决方案

这是一个偏执的东西做穿线。如果的其他的线程退订的最后一个处理的就在的你检查它,它可能的成为,你就会导致异常。由于代表是不可改变的,捕捉委托的快照到一个变量的发生停止这一点。



当然,它确实具备的其他的一面效果,即可以(代替)最终提高针对该认为一个对象的事件它已经取消订阅...



但是应力 - 这是只有一个问题,当多个线程被订阅/退订的对象,这是一种:罕见,和b:不完全理想的


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; 

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));
}

解决方案

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.

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...

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天全站免登陆