Question regarding to value/reference type of events(关于事件的价值/参考类型的问题)
问题描述
在 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.
这篇关于关于事件的价值/参考类型的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:关于事件的价值/参考类型的问题
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
