zoukankan      html  css  js  c++  java
  • C#多线程异常处理(四)

    在线程执行的地方使用try..catch..捕获不到异常
    首先,线程内部不应该出现异常,所以首选处理方式是在Task中使用try..catch..把异常处理掉
    Task中可能会抛出多个异常,应该使用AggregateException捕获多线程中所有异常。AggregateException是一个集合

    wait()、Result

    在调用Task的Wait()方法或Result属性处会抛出Task中的异常。

    使用ContinueWith捕获异常

    如果不可以在内部捕获,可以使用ContinueWith()方法捕获异常

      var t = Task.Run<int>(() =>
                     {
                         throw new Exception("error");
                         Console.WriteLine("action do do do");
                         return 1;
                     }).ContinueWith<Task<int>>((t1) => {
                         if (t1 != null && t1.IsFaulted)
                         {
                             Console.WriteLine(t1.Exception.Message);  //记录异常日志
                         }
                         return t1;
                     }).Unwrap<int>();
    

    上面使用起来比较麻烦,添加一个扩展方法:

     public static Task Catch(this Task task)
             {
                 return task.ContinueWith<Task>(delegate(Task t)
                 {
                     if (t != null && t.IsFaulted)
                     {
                         AggregateException exception = t.Exception;
                         Trace.TraceError("Catch exception thrown by Task: {0}", new object[]
                         {
                             exception
                         });
                     }
                     return t;
                 }).Unwrap();
             }
             public static Task<T> Catch<T>(this Task<T> task)
             {
                 return task.ContinueWith<Task<T>>(delegate(Task<T> t)
                 {
                     if (t != null && t.IsFaulted)
                     {
                         AggregateException exception = t.Exception;
                         Trace.TraceError("Catch<T> exception thrown by Task: {0}", new object[]
                         {
                             exception
                         });
                     }
                     return t;
                 }).Unwrap<T>();
             }
    

    捕获全局未观察到的异常

    TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs e)=> {
                    Console.WriteLine("捕获异常,"+e.Exception.InnerException.Message);
                };
    

    如何捕获async..await..异常:

    try{
      await task1;
    }
    catch{ 
    }
  • 相关阅读:
    iOS:解决打包可能会出现环境错误问题
    iOS:关于self.perfrom(:_, with: afterDelay: )不执行问题
    docker容器中安装vi命令
    java-1 基础一
    java-0 重拾java
    柯里化函数的实现
    flex布局最后一行列表左对齐的N种方法
    【第一弹】微服务认证与授权企业级理解
    MySQL性能优化(慢查询日志、Explain执行计划、show profile、MySQL服务优化)
    MySQL锁详解
  • 原文地址:https://www.cnblogs.com/xietianjiao/p/15188885.html
Copyright © 2011-2022 走看看