如何安全触发一个事件 [英] How do I fire an event safely

查看:141
本文介绍了如何安全触发一个事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在没有订阅一个事件我怎么保证,如果事件被触发一个异常不会被抛出。

  //委托报关
公众委托无效_delDisplayChange(对象发件人,字符串选项);

//事件声明
公共事件_delDisplayChange DisplayChange;

//抛出事件
DisplayChange(这一点,分配);


解决方案

下面是推荐的方式做到这一点:

 保护无效RaiseDisplayChanged(字符串消息)
{
VAR处理器= DisplayChange;
如果(处理!= NULL)
处理(这一点,消息);
}



复制事件处理程序枚举检查做了两件事之前:




  1. 如果DisplayChange处理程序成为检查和射击之间的空,你没死

  2. 如果听众修改DisplayChange名单,同时通过它枚举,你不会碰到的怪事。



此外,不使用标准的事件协议。您的代理应该是:



 公共委托无效DisplayChangeDelegate(对象发件人,OptionsEventArgs参数); 



在哪里OptionsEventArgs从EventArgs的派生。再进一步,在.net 3.5,你不应该这样定义的委托。相反,你应该只定义您的事件:

 公共事件的EventHandler< OptionsEventArgs> DisplayChanged; 



我喜欢把它甚至更进一步,定义这个类:

 公共类的EventArgs< T> :EventArgs的
{
公共牛逼载荷{搞定;私定}
公众的EventArgs(T负载)
{
=载荷有效载荷;
}
}



然后,你不需要定义OptionsEventArgs:

 公共事件的EventHandler< EventArgs的<串GT;> DisplayChanged; 



只是一些东西去思考...


When there are no subscribers to an event how do I ensure that an exception will not be thrown if the event is fired.

 // Delegate declaration
 public delegate void _delDisplayChange(object sender,string option);

 // Event declaration
 public event _delDisplayChange  DisplayChange;

 //throwing the event
 DisplayChange(this, "DISTRIBUTION");

解决方案

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...

这篇关于如何安全触发一个事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆