在C#中提高事件,忽略处理程序引发的异常 [英] Raising events in C# that ignore exceptions raised by handlers

查看:139
本文介绍了在C#中提高事件,忽略处理程序引发的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中提出事件的一个小宠物是事件处理程序中的异常会破坏我的代码,并且可能会阻止其他处理程序被调用,如果破碎的事件首先被调用;在大多数情况下,如果有人听到其事件的代码被破坏,我的代码不太在意。



我创建了一个捕获异常的扩展方法:

  public static void Raise(this EventHandler eh,object sender,EventArgs e)
{
if(eh == null )
return;
try
{
eh(sender,e);
}
catch {}
}

我的代码进行无论如何,此方法不会阻止第一个事件处理程序抛出异常并阻止第二个和后续处理程序被通知事件。我正在寻找一种迭代GetInvocationList的方法来将每个单独的事件处理程序包装在自己的try / catch中,但是这似乎效率很低,我并不确定最好的方法,即使我应该这样做。另外,我真的不太舒服,只是忽略这里的异常(而且FxCop / Resharper也不是这样);

解决方案

如果你这样做了,你该怎么办?

  public static void Raise(this EventHandler eh,object sender,EventArgs e)
{
if(eh == null)
返回;

foreach(eh.GetInvocationList()中的var handler)Cast< EventHandler>())
{
try
{
handler(sender,e );
}
catch {}
}
}


One of my pet peeves with raising events in C# is the fact that an exception in an event handler will break my code, and possibly prevent other handlers from being called, if the broken one happened to get called first; In most cases my code couldn't care less if somebody else's code that's listening to its events is broken.

I created an extension method that catches exceptions:

public static void Raise(this EventHandler eh, object sender, EventArgs e)
{
  if (eh == null)
    return;
  try
  {
    eh(sender, e);
  }
  catch { }
}

Although this does mean my code carries on regardless, this method doesn't stop a first event handler throwing an exception and preventing second and subsequent handlers being notified of the event. I'm looking into a way of iterating through GetInvocationList to wrap each individual event handler in it's own try/catch, but this seems inefficient, and I'm not certain of the best way to do it, or even if I should be.

Also, I'm really not comfortable simply ignoring the exception here (and neither's FxCop/Resharper for that matter); realistically what should happen to the exception in this case?

解决方案

What if you did something like this?

public static void Raise(this EventHandler eh, object sender, EventArgs e)
{
    if (eh == null)
        return;

    foreach(var handler in eh.GetInvocationList().Cast<EventHandler>())
    {
        try
        {
            handler(sender, e);
        }
        catch { }
    }
}

这篇关于在C#中提高事件,忽略处理程序引发的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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