Skip to content

Instantly share code, notes, and snippets.

@aliabidzaidi
Last active June 3, 2019 06:51
Show Gist options
  • Save aliabidzaidi/cd8cd7a77237a6c60c8373edb2e822d7 to your computer and use it in GitHub Desktop.
Save aliabidzaidi/cd8cd7a77237a6c60c8373edb2e822d7 to your computer and use it in GitHub Desktop.
Handling Custome Exceptions like operation Cancelled Exceptions
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
Task T1 = new Task(() => {
for(i=0;i<10000;i++){
token.ThrowIfCancellationRequested();
}
}, token);
Task T2 = new Task(() => { throw new IndexOutOfRangeException(); });
Task T3 = new Task(() => { Console.WriteLine("Task 3 did work"); });
T1.Start(); T2.Start(); T3.Start();
source.Cancel();
try{
Task.WaitAll(T1, T2, T3);
}
catch (AggregateException ex){
ex.Handle((inner) =>{
if (inner is OperationCanceledException){
return true; //Handled Exception
} else {
return false; //Unhandled Exception
}
});
}
Console.WriteLine("Task1 Completed:{0} Faulted:{1} IsCancelled:{2}", T1.IsCompleted, T1.IsFaulted, T1.IsCanceled);
//Console.WriteLine(T1.Exception);
Console.WriteLine("Task2 Completed:{0} Faulted:{1} IsCancelled:{2}", T2.IsCompleted, T2.IsFaulted, T2.IsCanceled);
//Console.WriteLine(T2.Exception);
Console.WriteLine("Task3 Completed:{0} Faulted:{1} IsCancelled:{2}", T3.IsCompleted, T3.IsFaulted, T3.IsCanceled);
//Console.WriteLine(T3.Exception);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment