在 C# 中引发事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1344972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:25:04  来源:igfitidea点击:

Raise an event in C#

c#eventsraise

提问by Long Ngo

I came across this question in a Microsoft Practice Test and I got confused. Here is the question:

我在 Microsoft 实践测试中遇到了这个问题,我感到很困惑。这是问题:

Which of the following C# code samples is the proper way to raise an event, assuming that the Alarm event, the AlarmEventArgs class, and the AlarmEventHandler delegate have been declared?

假设已声明 Alarm 事件、AlarmEventArgs 类和 AlarmEventHandler 委托,以下哪个 C# 代码示例是引发事件的正确方法?

Here is the "correct" answer they provided:

这是他们提供的“正确”答案:

AlarmEventArgs e = new AlarmEventArgs(1, 2);
AlarmEventHandler handler = Alarm; 
if (handler != null) 
{ 
    handler(this, e);
}

However, there is also another answer which seems correct.

但是,还有另一个似乎正确的答案。

AlarmEventArgs e = new AlarmEventArgs(1, 2);
if (Alarm!= null) 
{ 
    Alarm (this, e);
}

I personally, always use the second method. It works just fine. Can someone please tell me why I should use the first method instead of second?

我个人,总是使用第二种方法。它工作得很好。有人可以告诉我为什么我应该使用第一种方法而不是第二种方法吗?

回答by jeremyalan

In a multi-threaded environment, it's possible that the event handler may be updated while your event is being dispatched. To avoid this scenario, you assign the handler to a local variable before checking for null and dispatching the message.

在多线程环境中,事件处理程序可能会在调度事件时更新。为避免这种情况,您可以在检查 null 和分派消息之前将处理程序分配给局部变量。