我無法理解如何在TPL中處理異常。下面的代碼應該說明我的問題。在任務線程中拋出的異常,未被UnobservedTaskException捕獲
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace WebDLApp
{
class Program
{
static void Main(string[] args)
{
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; // Not catching exception
List<string> sites = new List<string>{ "http://microsoft.com", "http://yahoo.com", "http://facebook.com", "http://amazon.com", "http://foooo", "http://aol.com", "http://ask.com", "http://wikipedia.org" };
List<Task<string>> tasks = new List<Task<string>>();
foreach (string site in sites)
{
tasks.Add(Task.Factory.StartNew<string>((wsite) =>
{
using (WebClient wc = new WebClient())
{
wc.DownloadString((string)wsite); // Thrown here, always
return (string)wsite;
}
}, site)
);
}
Task.WaitAll(tasks.ToArray()); // Can't catch here
int counter = 1;
foreach (var task in tasks)
{
Console.WriteLine(counter.ToString() + task.Result); // Can't catch here either
counter++;
}
Console.ReadLine();
}
static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) // Never called
{
Console.WriteLine(e.Exception.Message);
e.SetObserved();
}
}
}
據我所知,使用TaskScheduler.UnobservedTaskException事件目的是幫助處理來自棘手的第三方庫例外一個很好的方式。但是,異常似乎總是在任務中拋出。它看起來好像永遠不會被TaskScheduler(或任何設備處理TaskExceptions)所捕獲。
爲簡潔起見,我省略了可能的try/catch位置並用註釋標記了它們。
我期待TaskScheduler_UnobservedTaskException事件處理程序打印到控制檯並觀察異常。但是,一旦執行達到任務的結果,WebException將從Task中拋出。
你還沒說你實際上看到的行爲。我猜你的'Task.WaitAll'調用正在拋出'AggregateException'。如果是這樣,那將是預期的行爲:你沒有任何未被察覺的例外。 'Wait' /'WaitAll' /'WaitAny'會傳播你正在等待的任務中的任何異常,此時它不再被觀察到。 –