Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise an event in C# [duplicate]

Tags:

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?

like image 707
Long Ngo Avatar asked Aug 28 '09 04:08

Long Ngo


People also ask

How do you raise an event?

Typically, to raise an event, you add a method that is marked as protected and virtual (in C#) or Protected and Overridable (in Visual Basic). Name this method On EventName; for example, OnDataReceived .

How do I invoke an event in C#?

Events in C# are simple things on the face of it. You create an event signature using a delegate type and mark it with the event keyword. External code can register to receive events. When specific things occur within your class, you can easily trigger the event, notifying all external listeners.

What is EventArgs C#?

The EventArgs class is the base class for all the event data classes. . NET includes many built-in event data classes such as SerialDataReceivedEventArgs. It follows a naming pattern of ending all event data classes with EventArgs. You can create your custom class for event data by deriving EventArgs class.


1 Answers

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.

like image 117
jeremyalan Avatar answered Oct 04 '22 20:10

jeremyalan