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         }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM