c# - 聚合事件异常
问题描述
我正在跟进一个教程,详细说明处理事件的多个订阅者中引发的事件。但是,当代码运行时,TargetInvocationException
catch 块不会捕获订阅者的方法体中抛出的异常:throw new Exception("Hello")
和throw new Exception("World")
分别。
相反,我在第一个侦听器中得到了一个未处理的异常错误,可以预见的是throw new Exception("Hello")
in private static void AlarmListener
。
尝试捕获被调用方法的异常时,我做错了什么?
class AggregatingExceptions
{
public void Main()
{
//create the alarm
AlarmAndLocation alarm = new AlarmAndLocation();
//subscribe the listeners
alarm.OnAlarmRaised += AlarmListener;
alarm.OnAlarmRaised += AlarmListener2;
try
{
alarm.RaiseAlarm("Kitchen");
}
catch (AggregateException agg)
{
foreach (Exception ex in agg.InnerExceptions)
{
Console.WriteLine(ex.Message);
}
}
}
private static void AlarmListener(object sender, AlarmEventArgs e)
{
Console.WriteLine("Alarm listener 1 called.");
throw new Exception("Hello");
}
private static void AlarmListener2(object sender, AlarmEventArgs e)
{
Console.WriteLine("Alarm listener 2 called.");
throw new Exception("World");
}
}
public class AlarmAndLocation
{
public event EventHandler<AlarmEventArgs> OnAlarmRaised = delegate { };
public List<Exception> exceptionList = new List<Exception>();
public void RaiseAlarm(string location)
{
foreach (Delegate handler in OnAlarmRaised.GetInvocationList())
{
try
{
handler.DynamicInvoke(this, new AlarmEventArgs(location));
}
catch (TargetInvocationException ex)
{
exceptionList.Add(ex.InnerException);
}
}
if(exceptionList.Count > 0)
{
throw new AggregateException(exceptionList);
}
}
}
public class AlarmEventArgs : EventArgs
{
public string Location { get; set; }
public AlarmEventArgs(string location)
{
Location = location;
}
}
解决方案
推荐阅读
- excel - 保护开启时图表代码不运行
- pact - Pact:如何匹配键与正则表达式匹配的对象?
- angular - 如何使用 ng2-signalr
- django - 如何访问 forms.py 定义中的运行时 request.session 值?
- r - 将 JSON 导出到文本文件
- javascript - 在 ngOnInit() 内部使用 ngOnInit() 外部的函数
- mysql - 如何使用 SELECT LAST_INSERT_ID(); 在mysql例程中插入语句后?
- python - 排序、排名、groupby 和 sum 组合 -> Python pandas
- c# - Sqlite 使用过程/触发器附加数据库,我将能够从 c# 运行它
- maven - 如何在每个环境中配置 Maven Surefire 中的环境变量?