Task.WaitAll,如何查找导致AggregateException的任务

时间:2013-08-19 12:41:02

标签: c# task-parallel-library

假设我得到以下代码:

var tasks = BuildTaskList();
try
{
    Task.WaitAll(tasks.ToArray());
}
catch (AggregateException exception)
{

}

我如何知道哪个任务在exception.InnerExceptions中提出了哪些例外?

4 个答案:

答案 0 :(得分:7)

您仍然拥有Tasks列表,每个Task都有Exception属性。使用它可以确定哪些例外属于哪个Task

但是,如果可以的话,最好使用Task.WhenAllTaskFactory.ContinueWhenAll而不是阻止等待。

答案 1 :(得分:2)

var throwers = tasks.Where(task => task.Exception != null);

答案 2 :(得分:0)

        var t1 = Task.Factory.StartNew(() => Console.WriteLine("Task 1"));
        var t2 = Task.Factory.StartNew(() => Console.WriteLine("Task 2"));
        var t3 = Task.Factory.StartNew(() => { throw new InvalidOperationException(); });
        var t4 = Task.Factory.StartNew(() => Console.WriteLine("Task 4"));

        Task.Factory.ContinueWhenAll(new[] { t1, t2, t3, t4 }, tasks =>
            {
                foreach (var t in tasks)
                {
                    if (t.Status == TaskStatus.Faulted)
                    {
                        // this will run for t3
                        Console.WriteLine("This task has been faulted.");
                    }
                }
            });

答案 3 :(得分:0)

选项1(提供给@ theodor-zoulias评论):

您可以使用任务名称设置Exception.Data属性:

var task1 = Task.Factory.StartNew(() =>
{
    try
    {
        throw new Exception();
    }
    catch (Exception exception)
    {
        exception.Data["task"] = "task1";
        throw exception;
    }
});

var task2 = Task.Factory.StartNew(() =>
{
    try
    {
        throw new Exception();
    }
    catch (Exception exception)
    {
        exception.Data["task"] = "task2";
        throw exception;
    }
});

try
{
    Task.WaitAll(task1, task2);
}
catch (AggregateException ae)
{
    foreach (var exception in ae.InnerExceptions)
    {
        Console.WriteLine($"Exception was thrown by {exception.Data["task"]}");
    }
}

选项2:

如果您不介意丢失异常的程序集信息的名称,则可以根据任务名称设置抛出的异常的Exception.Sourcedoc)属性,并在迭代时查看它:

var t1 = Task.Factory.StartNew(() => 
{
    throw new Exception() { Source = "t1" };
});
var t2 = Task.Factory.StartNew(() => 
{
    throw new Exception() { Source = "t2" };
});

try
{
    Task.WaitAll(t1, t2);
}
catch (AggregateException ae)
{
    foreach (var exception in ae.InnerExceptions)
    {
        Console.WriteLine($"Exception was thrown by {exception.Source}");
    }
}

将输出:

t1引发了异常

t2引发了异常