首页 > 解决方案 > 聚合事件异常

问题描述

我正在跟进一个教程,详细说明处理事件的多个订阅者中引发的事件。但是,当代码运行时,TargetInvocationExceptioncatch 块不会捕获订阅者的方法体中抛出的异常: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;
    }
}

标签: c#exceptioneventslisteneraggregateexception

解决方案


推荐阅读