Asynchronous code and exceptions

There are 2 kinds of coding when handling asynchronous code.

The first one is  calling Result:

< [code lang="csharp"] t.TwoTask().Result [/code]

The second is async /await

public async Task&lt;bool&gt; TwoTask() {

//code

await Task.WhenAll(file,console);
return file.Result &amp; 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(&quot;Aggregate number of exceptions :&quot;+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 &amp; console.Result;
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(&quot;Exception is &quot; + ex.Message);
                
                if (file.IsFaulted)
                {
                    Console.WriteLine(&quot;file is faulted exceptions :&quot; + file.Exception.InnerExceptions.Count);
                    
                }
                if (console.IsFaulted)
                {
                    Console.WriteLine(&quot;console is faulted exceptions :&quot; + console.Exception.InnerExceptions.Count);
                }
                
                throw;
            }

Maybe it is better when you see a video demo: Async await and exceptions at https://youtu.be/1a9s74IfSE8


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *