如何处理多播委托例外在C#中? [英] How to handle exception in multicast delegate in C#?
问题描述
我一直在考虑一些代码,我通过多播委托调用。
I've been given some code that I am calling through multicast delegate.
我想知道我怎么能赶上和管理提出了有什么异常,未的时刻进行管理。我不能修改给出的代码。
I would like to know how I can catch up and manage any exception raised there and that is not managed for the moment. I cannot modify the code given.
我一直在找了一圈,发现大约需要调用GetInvocationList(),但不能确定这是否是有帮助的。
I've been looking around and found about the need to call GetInvocationList() but not really sure if this is helpful.
推荐答案
使用 GetInvocationList
考虑代码:
foreach (var handler in theEvent.GetInvocationList().Cast<TheEventHandler>()) {
// handler is then of the TheEventHandler type
try {
handler(sender, ...);
} catch (Exception ex) {
// uck
}
}
这我的老办法,新办法,我更喜欢超过,因为它使调用一个单元,包括使用了/ ref参数(如果需要)。
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)
编码愉快。
的事件处理时,请记住做标准空后卫copy'n'check(也许锁)。
Remember to do the standard null-guard copy'n'check (and perhaps lock) when dealing with events.
这篇关于如何处理多播委托例外在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!