當使用Task.WaitAll等待任務並指定超時(如果WaitAll超時)時,我還必須單獨觀察任何未完成的任務(例如,通過註冊延續)?任務和Task.WaitAll具有超時異常處理
This thread讓我覺得答案是肯定的,但我還沒有發現任何證實這一點的東西。
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);
}
在WaitAll後捕獲的AggregateException中存在多少個異常? –
完整的簡單lib源代碼在這裏:http://stackoverflow.com/questions/11831844/unobservedtaskexception-being-throw-but-it-is-handled-by-a-taskscheduler-unobser – 2013-01-21 15:30:42