我无法理解 TPL 中如何处理异常。下面的代码应该可以说明我的问题。
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。
最佳答案
Here (How to handle exceptions with TaskScheduler.UnobservedTaskException?)是解释。 只需更换
Task.WaitAll(tasks.ToArray()); // Can't catch here
与
Task.Factory.StartNew(() =>
{
while (true)
{
Thread.Sleep(1000);
GC.Collect();
}
});
return;
在 TaskScheduler_UnobservedTaskException
中查看消息
关于c# - 任务线程中抛出的异常,未被 UnobservedTaskException 捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10874068/