在调用Task的Wait()方法或Result属性处会抛出Task中的异常。
但是如果没有返回结果,或者不想调用Wait()方法,该怎么获取异常呢?
可以使用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 }
原文:https://www.cnblogs.com/fanfan-90/p/12006518.html