簡體   English   中英

任務線程中拋出的異常,未被UnobservedTaskException捕獲

[英]Exception thrown in Task Thread, not caught by UnobservedTaskException

我無法理解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事件對象是一種幫助處理棘手的第三方庫異常的好方法。 但是,異常似乎總是在Task中拋出。 看起來它似乎永遠不會被TaskScheduler(或任何工具處理TaskExceptions)捕獲。

為了簡潔起見,我省略了可能的try / catch位置並用注釋標記它們。

我期待TaskScheduler_UnobservedTaskException事件處理程序打印到控制台並觀察異常。 但是,一旦執行到達任務的結果,就會從Task中拋出WebException。

這里(如何使用TaskScheduler.UnobservedTaskException處理異常?)是解釋。 只需更換

Task.WaitAll(tasks.ToArray()); // Can't catch here

Task.Factory.StartNew(() =>
{
    while (true)
    {
        Thread.Sleep(1000);
        GC.Collect();
    }
});
return;

TaskScheduler_UnobservedTaskException查看消息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM