c# - 为什么将事件处理程序复制到另一个变量中

标签 c#

在一个例子中,我找到了这个代码:

public event EventHandler ThresholdReached;

protected virtual void OnThresholdReached(EventArgs e)
{
  EventHandler handler = ThresholdReached;
  if (handler != null)
            handler(this, e);
}

我想了解该行的原因:
EventHandler handler = ThresholdReached;

我们能不能不这样做:
public event EventHandler ThresholdReached;

protected virtual void OnThresholdReached(EventArgs e)
{
  if (ThresholdReached != null)
            ThresholdReached(this, e);
}

这两种方式是否有一些优点/缺点?

最佳答案

在第二个版本中存在线程竞争的理论风险,即有人取消订阅检查和调用之间的事件,导致 NullReferenceException在调用步骤中。将值捕获到本地并进行测试/调用以防止这种情况发生。但是,也许可以使用 C# 6 或更高版本的第三个版本(感谢 @Cid):

ThresholdReached?.Invoke(this, e);

这基本上是第一个版本的简写版本 - 所有的安全性,但现在简洁。

关于c# - 为什么将事件处理程序复制到另一个变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59301612/

相关文章:

c# - 基本的用户输入字符串验证

c# - WebAPI token 颁发授权

c# - 如何从XNode读取数据

c# - 发送批量电子邮件时出错 "An asynchronous call is already in progress. It must be completed or canceled before you can call this method"

c# - 内存泄漏问题 : how to dispose a SignalR hub connection and when to create a new connection

c# - IOC-容器使用。 key 不能为空。参数名称 : key

c# - 抓取位于 div 正下方的 html

c# - System.Linq 和 System.Data.Linq 有什么区别?

c# - 如何替换 MEF 容器中导出的部件/对象?

c# - 处理时动画托盘图标