c# - 任务线程中抛出的异常,未被 UnobservedTaskException 捕获

标签 c# multithreading exception task-parallel-library

我无法理解 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/

相关文章:

C# 生成新线程然后等待

c# - 对象名称 dbo 表名无效 - Entity Framework 适用于 IIS,但不适用于 Azure 应用服务

c# - ReactiveUI命令退订

c# - 如何捕获 Action<T> 中的异常或包含 C# 中的匿名方法的异常?

python - 为什么python属性装饰器会吃掉这个异常?

c# - 如何生成for循环

java - 客户端可以同时向多个服务器发送消息吗?

java - 两个线程交互会减慢彼此的速度吗?

android - 如何从后台线程向主线程发送位图数据?

c# - ASP.Net MVC - "Cannot Create Instance of an Interface"