TaskScheduler.UnobservedTaskException event handler never being triggered

后端 未结 3 949
执笔经年
执笔经年 2020-12-03 02:54

I\'m reading through a book about the C# Task Parallel Library and have the following example but the TaskScheduler.UnobservedTaskException handler is never being triggered.

3条回答
  •  误落风尘
    2020-12-03 03:05

    The exception won't be "unobserved" in that sample snippet. Not until the garbage collector gets rid of the Task instances. You'd have to rewrite it like this:

    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);
            }
        }
    }
    

    Don't do this, use Task.Wait().

提交回复
热议问题