olidev
olidev

Reputation: 20644

How to safely trigger an event?

I am not sure whether is this the way to trigger an event in C#:

public event EventHandler<ActionEventArgs> ActionDataReceived;

public void showLog(string logMessage)
{
   ActionDataReceived(this, new ActionEventArgs(logMessage));
}

Upvotes: 2

Views: 102

Answers (2)

James
James

Reputation: 82096

The safe way is to take a copy of the handler and raise that instead i.e.

var handler = ActionDataReceived;
if (handler != null)
{
    handler(this, new ActionEventArgs(logMessage));
}

This will mitigate the race condition that could lead to the event being unassigned before you attempt to raise it.


As @EricLippert has pointed out this does not cover the scenario where the internal state of the handler is changed after the assignment has occurred.

Upvotes: 5

daryal
daryal

Reputation: 14919

var temp = ActionDataReceived;
if (temp != null)
      temp();

You may refer to this post of Eric Lippert for detailed explanation.

Upvotes: 0

Related Questions