Last active
June 3, 2019 07:40
-
-
Save aliabidzaidi/9cd5d35c539b68dfe9506338b88f4a48 to your computer and use it in GitHub Desktop.
A simple way to handle Exceptions thrown by tasks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Task T1 = new Task(() => { throw new ArgumentOutOfRangeException() { Source = "T1"}; }); | |
Task T2 = new Task(() => { throw new NullReferenceException(); }); | |
Task T3 = new Task(() => { Console.WriteLine("Artificial Cancellation"); throw new OperationCanceledException(); }); | |
T1.Start(); T2.Start(); T3.Start(); | |
try{ | |
Task.WaitAll(T1, T2, T3); | |
} | |
catch (AggregateException ex){ | |
//1 Simple Example of Handling Exception | |
foreach (Exception inner in ex.InnerExceptions) | |
{ | |
Console.WriteLine("Exception {0} : from {1}", inner.GetType(), inner.Source); | |
} | |
//2 Using Iterative Event Handler | |
ex.Handle((inner) =>{ | |
if (inner is OperationCanceledException){ | |
return true; //Handled Exception | |
} else { | |
return false; //Unhandled Exception | |
} | |
}); | |
} | |
//Useful properties in Task instance | |
Console.WriteLine("Task1 Completed:{0} Faulted:{1} IsCancelled:{2} Exception:{3}", T1.IsCompleted, T1.IsFaulted, T1.IsCanceled, T1.Exception); | |
Console.WriteLine("Task2 Completed:{0} Faulted:{1} IsCancelled:{2} Exception:{3}", T2.IsCompleted, T2.IsFaulted, T2.IsCanceled, T1.Exception); | |
Console.WriteLine("Task3 Completed:{0} Faulted:{1} IsCancelled:{2} Exception:{3}", T3.IsCompleted, T3.IsFaulted, T3.IsCanceled, T1.Exception); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment