Task of the call Wait () method or the Result property of the Task exception will be thrown in.
But if no results are returned, or do not want to call the Wait () method, how to get it abnormal?
You can use the ContinueWith () method
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); // record exception log 10 } . 11 return T1; 12 is .}) The Unwrap < int > ();
The above is too much trouble to use, add an extension method:
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 }