How to handle exception in multicast delegate in C#?

▼魔方 西西 提交于 2019-12-01 07:31:50

Consider the code using GetInvocationList:

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

This my old approach, the newer approach I prefer is above because it makes invocation a snap, including the use of out/ref parameters (if desired).

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

which individually calls each delegate that would have been invoked with

 theEvent.Invoke(sender, eventArg)

Happy coding.


Remember to do the standard null-guard copy'n'check (and perhaps lock) when dealing with events.

You can loop through all the delegates registed in the multicast list and call each of them in turn while wrapping each call in a try - catch block.

Otherwise the invocations of the subsequent delegates in the multicast after the delegate with the exception will be aborted.

The upvoted answer is for events, for delegates specifically try this extension method:

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