Task.WaitAll和异常 [英] Task.WaitAll and Exceptions

查看:943
本文介绍了Task.WaitAll和异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于Task.WaitAll和异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆