zoukankan      html  css  js  c++  java
  • C#异步编程之:(三)使用TaskScheduler.UnobservedTaskException

    不多解释,抄书了:

    If you don’t catch AggregateException when you call a trigger method, the .NET Framework will escalate the exceptions. By default, this means that the unhandled exceptions will be thrown again when your Task is finalized and cause your program to be terminated. Because you don’t know when the finalizer will be called, you won’t be able to predict when this will happen. But, you can override the escalation policy and supply your own code to call when an exception is escalated. You do this by adding an event handler to the static System.Threading.Tasks.TaskScheduler.UnobservedTaskException member.


    书里面的实例根本没法用,永远不会触发Task对象的析构!所以我改写了下,而且书里面是2个方法都用了,其实任何一个方法都能处理异常!


    using System;
    using System.Collections;
    using System.Threading.Tasks;
    
    namespace Listing_22
    {
        class Listing_22
        {
            static void Main(string[] args)
            {
                TaskScheduler.UnobservedTaskException +=
                    (object sender, UnobservedTaskExceptionEventArgs eventArgs) =>
                    {
                        // 阻止程序崩溃的方法有2种
                        
                        //第一种是:
                        {
                            eventArgs.SetObserved();
                            Console.WriteLine("Exception handled");
                        }
    
                        //第二种,返回true
                        if (false)
                        {
                            ((AggregateException)eventArgs.Exception).Handle(ex =>
                            {
                                Console.WriteLine("Exception handled");
                                return true;
                            });
                        }
                    };
    
                RunTask();
    
                // 不断分配内存,强制让GC收集Task对象,从而触发UnobservedTaskException
                ArrayList arr = new ArrayList();
                while (true)
                {
                    char[] array = new char[100000];
                    arr.Add(array);
                    GC.Collect();
                }
            }
    
            private static void RunTask()
            {
                new Task(() => { throw new NullReferenceException(); }).Start();
            }
        }
    }
    


  • 相关阅读:
    IDEA 工具 破解码
    postman 使用 及断言
    MonkeyTest 命名
    Jmeter 测试单元的封装与复用
    开发性能测试工具——自己动手实现迭代功能
    jemter安装mysql数据驱动JDBC
    全链路性能测试知识点整理
    Java接口全链路优化:如何降低接口RT时长(转)
    测试自动化之Mock服务思路探讨
    算法分析与设计(一)时间与空间复杂度
  • 原文地址:https://www.cnblogs.com/puncha/p/3877013.html
Copyright © 2011-2022 走看看