tags:

views:

795

answers:

2

I cam across this question in a Microsoft Practice Test and get 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 provide:

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

However, there are 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?

Thanks Long

+3  A: 

I asked a similar question. The accepted answer is a good explanation.

http://stackoverflow.com/questions/282653/checking-for-null-before-event-dispatching-thread-safe

spender
The anonymous delegate method proposed by the user 'Cherian' is just beautiful. Hands-down the winner :)
Noon Silk
Once you get you head round the somewhat functional concept that empty handlers are ok
spender
+1  A: 

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.

ph0enix