Task.WaitAll和异常异常、Task、WaitAll

由网友(苡为会緈幅)分享简介:我有一个异常处理和并行任务出现了问题。I have a problem with exception handling and parallel tasks.下面显示的code开头2个任务,并等待他们完成。我的问题是,如果一个任务抛出一个异常,catch处理从未达到过。The code shown below s...

我有一个异常处理和并行任务出现了问题。

I have a problem with exception handling and parallel tasks.

下面显示的code开头2个任务,并等待他们完成。我的问题是,如果一个任务抛出一个异常,catch处理从未达到过。

The code shown below starts 2 tasks and waits for them to finish. My problem is, that in case a task throws an exception, the catch handler is never reached.

        List<Task> tasks = new List<Task>();
        try
        {                
            tasks.Add(Task.Factory.StartNew(TaskMethod1));
            tasks.Add(Task.Factory.StartNew(TaskMethod2));

            var arr = tasks.ToArray();                
            Task.WaitAll(arr);
        }
        catch (AggregateException e)
        {
            // do something
        }

然而,当我用下面的code等待一个超时的任务,将抛出异常。

However when I use the following code to wait for the tasks with a timeout, the exception is caught.

 while(!Task.WaitAll(arr,100));

我似乎失去了一些东西,作为为WaitAll 的说明文件描述了我的第一次尝试是正确的。请帮我理解为什么它不能正常工作。

I seem to be missing something, as the documentation for WaitAll describes my first attempt to be the correct one. Please help me in understanding why it is not working.

推荐答案

无法重现这一点 - 它为我工作正常:

Can't reproduce this - it works fine for me:

using System;
using System.Threading;
using System.Threading.Tasks;

class Test
{
    static void Main()
    {
        Task t1 = Task.Factory.StartNew(() => Thread.Sleep(1000));
        Task t2 = Task.Factory.StartNew(() => {
            Thread.Sleep(500);
            throw new Exception("Oops");
        });

        try
        {
            Task.WaitAll(t1, t2);
            Console.WriteLine("All done");
        }
        catch (AggregateException)
        {
            Console.WriteLine("Something went wrong");
        }
    }
}

这版画出事了,就像我期待的。

That prints "Something went wrong" just as I'd expect.

难道你的任务之一是不是完了? 为WaitAll 确实等待所有的任务完成,即使有些已经失败了。

Is it possible that one of your tasks isn't finished? WaitAll really does wait for all the tasks to complete, even if some have already failed.

阅读全文

相关推荐

最新文章