zoukankan      html  css  js  c++  java
  • Task异常捕获的几种方式

    在线程执行的地方使用try..catch..捕获不到异常,在调用Task的Wait()方法或Result属性处会抛出Task中的异常。

    Task中可能会抛出多个异常,应该使用AggregateException捕获多线程中所有异常。AggregateException是一个集合

    但是如果没有返回结果,或者不想调用Wait()方法,该怎么获取异常呢? 

    首先,线程内部不应该出现异常,所以首选处理方式是在Task中使用try..catch..把异常处理掉

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

     1  var t = Task.Run<int>(() =>
     2                 {
     3                     throw new Exception("error");
     4                     Console.WriteLine("action do do do");
     5                     return 1;
     6                 }).ContinueWith<Task<int>>((t1) => {
     7                     if (t1 != null && t1.IsFaulted)
     8                     {
     9                         Console.WriteLine(t1.Exception.Message);  //记录异常日志
    10                     }
    11                     return t1;
    12                 }).Unwrap<int>();

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

     1 public static Task Catch(this Task task)
     2         {
     3             return task.ContinueWith<Task>(delegate(Task t)
     4             {
     5                 if (t != null && t.IsFaulted)
     6                 {
     7                     AggregateException exception = t.Exception;
     8                     Trace.TraceError("Catch exception thrown by Task: {0}", new object[]
     9                     {
    10                         exception
    11                     });
    12                 }
    13                 return t;
    14             }).Unwrap();
    15         }
    16         public static Task<T> Catch<T>(this Task<T> task)
    17         {
    18             return task.ContinueWith<Task<T>>(delegate(Task<T> t)
    19             {
    20                 if (t != null && t.IsFaulted)
    21                 {
    22                     AggregateException exception = t.Exception;
    23                     Trace.TraceError("Catch<T> exception thrown by Task: {0}", new object[]
    24                     {
    25                         exception
    26                     });
    27                 }
    28                 return t;
    29             }).Unwrap<T>();
    30         }

     

  • 相关阅读:
    centOS7虚拟机连接大网
    [CSP-S模拟测试48]反思+题解
    [CSP-S模拟测试47]反思+题解
    [bzoj2456]mode 题解
    [CSP-S模拟测试45]题解
    [CSP模拟测试43、44]题解
    [CSP-S模拟测试41]题解
    [NOIP模拟测试38]题解
    一些idea
    [NOIP模拟测试37]反思+题解
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/12006518.html
Copyright © 2011-2022 走看看