问题描述
我在异常处理和并行任务方面遇到问题.
I have a problem with exception handling and parallel tasks.
下面显示的代码启动 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
}
但是,当我使用以下代码等待超时的任务时,异常被捕获.
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 和异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!