c#中如何处理多播委托中的异常

本文关键字:多播 异常 处理 何处理 | 更新日期: 2023-09-27 17:50:39

我得到了一些代码,我通过多播委托调用。

我想知道我如何赶上并管理那里提出的任何异常,并且目前没有管理。我不能修改给定的代码。

我一直在四处寻找,发现需要调用GetInvocationList(),但不确定这是否有帮助。

c#中如何处理多播委托中的异常

考虑使用GetInvocationList:

的代码
foreach (var handler in theEvent.GetInvocationList().Cast<TheEventHandler>()) {
   // handler is then of the TheEventHandler type
   try {
      handler(sender, ...);
   } catch (Exception ex) {
      // uck
   }
}   

这是我的旧方法,我更喜欢上面的新方法,因为它使调用变得简单,包括使用out/ref参数(如果需要)。

foreach (var singleDelegate in theEvent.GetInvocationList()) {
   try {
      singleDelgate.DynamicInvoke(new object[] { sender, eventArg });
   } catch (Exception ex) {
      // uck
   }
}

单独调用将使用

调用的每个委托。
 theEvent.Invoke(sender, eventArg)

幸福的编码。


请记住在处理事件时执行标准的null保护复制检查(可能还有锁定)。

您可以循环遍历在多播列表中注册的所有委托,并依次调用它们中的每个,同时将每个调用包装在try - catch块中。

否则,在具有异常的委托之后的组播中后续委托的调用将被中止。

赞成的答案是事件,代表特别尝试这个扩展方法:

    public static class DelegateExtensions
{
    public static void SafeInvoke(this Delegate del,params object[] args)
    {
        foreach (var handler in del.GetInvocationList())
        {
            try
            {
                    handler.Method.Invoke(handler.Target, args);
            }
            catch (Exception ex)
            {
                // ignored
            }
        }
    }
}