Asynchronous code and exceptions
There are 2 kinds of coding when handling asynchronous code.
The first one is calling Result:
<
The second is async /await
public async Task<bool> TwoTask() { //code await Task.WhenAll(file, console); return file.Result & console.Result; }
As such, we will have 2 intercepting code.
For the first one we will catch AggregateException
try { Console.WriteLine(t.TwoTask().Result); } catch (AggregateException ex) { Console.WriteLine("Aggregate number of exceptions :"+ex.InnerExceptions.Count); }
For the second one we will catch the FIRST task exception ( or , more generic , Exception ) – and see what other tasks have been doing
try
try { await Task.WhenAll(file, console); return file.Result & console.Result; } catch (ArgumentException ex) { Console.WriteLine("Exception is " + ex.Message); if (file.IsFaulted) { Console.WriteLine("file is faulted exceptions :" + file.Exception.InnerExceptions.Count); } if (console.IsFaulted) { Console.WriteLine("console is faulted exceptions :" + console.Exception.InnerExceptions.Count); } throw; }
Maybe it is better when you see a video demo: Async await and exceptions at https://youtu.be/1a9s74IfSE8
Leave a Reply