How do I fire an event safely

二次信任 提交于 2019-12-04 17:24:56

Here is the recommended way to do it:

protected void RaiseDisplayChanged(string message)
{
    var handlers = DisplayChange;
    if(handlers != null)
        handlers(this, message);
}

Copying the event handlers enumeration before checking does two things:

  1. If DisplayChange handlers becomes null between the check and the firing, you don't die
  2. If the listeners modify the DisplayChange list while enumerating through it, you don't run into oddities.

Also, you are not using the standard Event protocol. Your delegate should be:

public delegate void DisplayChangeDelegate(object sender, OptionsEventArgs args);

Where OptionsEventArgs derives from EventArgs. Going a step further, in .Net 3.5, you should never define a delegate like this. Instead, you should just define your event:

public event EventHandler<OptionsEventArgs> DisplayChanged;

I like to take it even one step further by defining this class:

public class EventArgs<T> : EventArgs
{
    public T Payload { get; private set }
    public EventArgs(T payload)
    {
        Payload = payload;
    }
}

Then, you don't need to define OptionsEventArgs:

public event EventHandler<EventArgs<string>> DisplayChanged;

Just some stuff to think about...

Change this:

// Event declaration      
public event _delDisplayChange  DisplayChange;

to this:

// Event declaration      
public event _delDisplayChange  DisplayChange = delegate{};

This will ensure your event will always have at least one subscriber.

As Brian said: many sources suggest making a copy of the event before checking that it is not null:

_delDisplayChange displayChangeCopy = DisplayChange;
if (displayChangeCopy != null)
    displayChangeCopy(this, "DISTRIBUTION");

This helps to make your code more thread-safe because the value of displayChangeCopy will not change between the null check and the invocation.

pFrenchie

Further to Jay's answer, here's a link regarding performance considerations when using empty delegates.

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