关于事件的价值/参考类型的问题

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)