How to handle exceptions occured in the delegate target
I have a delegate which points to 3 different methods. These methods are added in its invocation list.
What is second method throws an exception??? I still need to execute the third method.
I think one alternative is below mentioned code
public delegate void MethodHandler();
A oa = new A();
B ob = new B();
C oc = new C();
D od = new D();
MethodHandler M = oa.TestM;
M += ob.TestM;
M += oc.TestM;
M += od.TestM;
foreach (Delegate item in M.GetInvocationList())
{
开发者_JAVA技巧 try
{
item.DynamicInvoke(null);
}
catch
{
}
}
Is there any other alternative to avoid this?
You're not going to be able to "avoid" this in the sense of not using a try
/catch
pattern to ensure your code proceeds past a delegate that threw an exception.
Nothing's stopping you from writing your own class to wrap this functionality, though -- to mitigate the potential proliferation of this exact code everywhere you're using your M
delegate.
By the way, I believe you can change this line:
item.DynamicInvoke(null);
to this (to avoid the DynamicInvoke
):
MethodHandler handler = (MethodHandler)item;
handler.Invoke();
精彩评论