How to handle exception in multicast deletion in C #?

I was given some code that I call through the multicast delegate.

I would like to know how I can catch up with and manage any exception raised there, and at the moment it is not controlled. I cannot change the specified code.

I looked around and found the need to call GetInvocationList (), but not quite sure if this is useful.

+4
source share
3 answers

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 is my old approach, the newer approach that I prefer is higher because it calls for binding, including using 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 be called using

  theEvent.Invoke(sender, eventArg) 

Happy coding.


Remember to make a standard copy of null-guard copy'n'check (and possibly block) when working with events.

+4
source

You can scroll through all the delegates registered on the multicast list and call each of them in turn, wrapping each call in a try-catch block.

Otherwise, calls to subsequent delegates in multicast after the delegate with exception will be interrupted.

+2
source

The selected answer is for events, as delegates specifically use 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 } } } } 
0
source

All Articles