39

我正在阅读一本关于 C# 任务并行库的书,并有以下示例,但从未触发 TaskScheduler.UnobservedTaskException 处理程序。谁能给我任何关于为什么的线索?

TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs eventArgs) =>
{
    eventArgs.SetObserved();
    ((AggregateException)eventArgs.Exception).Handle(ex =>
    {
        Console.WriteLine("Exception type: {0}", ex.GetType());
        return true;
    });
};

Task task1 = new Task(() => 
{
    throw new ArgumentNullException();
});

Task task2 = new Task(() => {
    throw new ArgumentOutOfRangeException();
});

task1.Start();
task2.Start();

while (!task1.IsCompleted || !task2.IsCompleted)
{
    Thread.Sleep( 5000 );
}

Console.WriteLine("done");
Console.ReadLine();
4

3 回答 3

61

不幸的是,该示例永远不会向您展示您的代码。只有当UnobservedTaskException任务被 GC 收集且未观察到异常时才会发生 - 只要您持有对task1and的引用task2,GC 将永远不会收集,并且您将永远不会看到您的异常处理程序。

为了查看实际操作的行为UnobservedTaskException,我会尝试以下(人为的示例):

public static void Main()
{
    TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs eventArgs) =>
                {
                    eventArgs.SetObserved();
                    ((AggregateException)eventArgs.Exception).Handle(ex =>
                    {
                        Console.WriteLine("Exception type: {0}", ex.GetType());
                        return true;
                    });
                };

    Task.Factory.StartNew(() =>
    {
        throw new ArgumentNullException();
    });

    Task.Factory.StartNew(() =>
    {
        throw new ArgumentOutOfRangeException();
    });


    Thread.Sleep(100);
    GC.Collect();
    GC.WaitForPendingFinalizers();

    Console.WriteLine("Done");
    Console.ReadKey();
}

这将显示您的消息。第一次Thread.Sleep(100)调用为任务抛出提供了足够的时间。收集和等待强制 GC 收集,这将触发您的事件处理程序 2x。

于 2010-07-19T19:23:54.000 回答
4

该示例片段中不会“未观察到”异常。直到垃圾收集器摆脱 Task 实例。你必须像这样重写它:

class Program {
    static void Main(string[] args) {

        TaskScheduler.UnobservedTaskException += ( object sender, UnobservedTaskExceptionEventArgs eventArgs ) =>
        {
            eventArgs.SetObserved();
            ( (AggregateException)eventArgs.Exception ).Handle( ex =>
            {
                Console.WriteLine("Exception type: {0}", ex.GetType());
                return true;
            } );
        };

        Run();

        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("done");
        Console.ReadLine();
    }

    static void Run() {
        Task task1 = new Task(() => {
            throw new ArgumentNullException();
        });

        Task task2 = new Task(() => {
            throw new ArgumentOutOfRangeException();
        });

        task1.Start();
        task2.Start();

        while (!task1.IsCompleted || !task2.IsCompleted) {
            Thread.Sleep(50);
        }
    }
}

不要这样做,使用 Task.Wait()。

于 2010-07-19T19:28:22.110 回答
1

我在 .NET 4.5、Visual Studio 2012(调试或发布,没关系)上运行此代码,我没有ThrowUnobservedTaskException放在我的 app.config 中:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace Test
{
    public static class Program
    {
        private static void Main()
        {
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            RunTask();

            Thread.Sleep(2000);

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            Console.ReadLine();
        }

        static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            Console.WriteLine("Caught!");
        }

        private static void RunTask()
        {
            Task<int> task = Task.Factory.StartNew(() =>
            {
                Thread.Sleep(1000); // emulate some calculation
                Console.WriteLine("Before exception");
                throw new Exception();
                return 1;
            });
        }
    }
}

异常被 UnobservedTaskException 处理程序捕获(打印“Caught!”)。

于 2014-06-14T21:58:17.753 回答