任务和任务.WaitAll具有超时异常处理

Law*_*ton 5 c# task-parallel-library

当使用Task.WaitAll等待任务并在WaitAll超时时指定超时时,我还必须单独观察任何未完成的任务(例如通过注册延续)?

这个帖子让我觉得答案是肯定的,但我还没有找到其他证实这一点的东西.

var random = new Random();
var tasks = Enumerable.Range(0, 10).Select((i) => Task.Factory.StartNew(() => {
        // Sleep 5-15 seconds
        Thread.Sleep(random.Next(5000, 15000));
        throw new Exception("Some exception.");
    }
)).ToArray();

try {
    // Wait for 10 seconds
    Task.WaitAll(tasks, 10000);
} catch (AggregateException) {
    // Swallow
}

// Check to see how many tasks were unfinished
tasks.Where(t => !t.IsCompleted).Count().Dump("Unfinished count: ");

// Is this neccessary to avoid exceptions being thrown on the finalizer?
foreach (Task task in tasks) {
    task.ContinueWith(t => t.Exception, TaskContinuationOptions.OnlyOnFaulted);
}
Run Code Online (Sandbox Code Playgroud)

Law*_*ton 1

使用 LINQPad v4.31 进行的测试表明答案是肯定的,因为如果注释掉 foreach,每个未完成的任务都会出现一个未处理的异常对话框。

我相信我现在明白为什么会这样,但如果有人想尝试对这种行为进行更技术性的解释,请务必去做。