Raise an event in C# [duplicate]

≡放荡痞女 提交于 2019-12-04 15:46:59

问题


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

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?

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?


回答1:


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.



来源:https://stackoverflow.com/questions/1344972/raise-an-event-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!