使用未观察到的异常查找任务的最佳策略

时间:2015-12-03 12:20:11

标签: c# .net async-await task-parallel-library

假设我有以下代码:

private static void Run()
{
    TaskScheduler.UnobservedTaskException += delegate { Console.WriteLine("Unobserved task exception!"); };

    try
    {
        RunAsync().Wait();
    }
    catch (Exception)
    {
    }

    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();

    Thread.Sleep(Timeout.InfiniteTimeSpan);
}

private static async Task RunAsync()
{
    var task1 = ThrowAsync();
    var task2 = ThrowAsync();

    await task1;
    await task2;
}

private static async Task ThrowAsync()
{
    throw new Exception("Test exception");
}

此代码输出Unobserved task exception!,因为未发现task2中的异常。

我的问题如下:有没有办法以编程方式确定哪个任务有未观察到的异常?例如,我想获取一个调用任务的方法的堆栈跟踪:

Unobserved exception: task2 in RunAsync()

可悲的是,异常堆栈跟踪是不够的。上面的代码只是一个演示,在实际的应用程序中,我有时会有一些未观察到的任务异常,其堆栈跟踪如下:

System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Web.HttpApplication.get_CurrentModuleContainer()
   at System.Web.HttpApplication.PipelineStepManager.ResumeSteps(Exception error)

1 个答案:

答案 0 :(得分:1)

一个人就能知道哪个Task实例的异常未被观察到。那将是第二个lib/src.zip

下的task2
await

因为第一个await task1; await task2; “观察”了await的结果。

然后,如果事件处理程序被修改为呈现task1提供的实际Task异常

TaskScheduler.UnobservedTaskException

然后可以通过观察异常的堆栈跟踪来跟踪任务代码的失败区域:

    TaskScheduler.UnobservedTaskException += delegate(object o, UnobservedTaskExceptionEventArgs ea)
    {
        Console.WriteLine($"Unobserved task exception! {ea.Exception.ToString()}");
    };

希望如此。