我已经获得了一些通过多播委托(delegate)调用的代码。
我想知道我如何 catch 并管理那里提出的任何异常,但目前还没有管理。我无法修改给定的代码。
我一直在四处寻找并发现需要调用 GetInvocationList() 但不确定这是否有用。
最佳答案
考虑使用 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
}
}
它单独调用每个将被调用的委托(delegate)
theEvent.Invoke(sender, eventArg)
快乐编码。
记住在处理事件时执行标准的 null-guard copy'n'check(可能还有锁定)。
关于c# - 如何在 C# 中处理多播委托(delegate)中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9764084/