Skip to content

Instantly share code, notes, and snippets.

@aliabidzaidi
Last active June 3, 2019 07:40
Show Gist options
  • Save aliabidzaidi/9cd5d35c539b68dfe9506338b88f4a48 to your computer and use it in GitHub Desktop.
Save aliabidzaidi/9cd5d35c539b68dfe9506338b88f4a48 to your computer and use it in GitHub Desktop.
A simple way to handle Exceptions thrown by tasks
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