How to Use Await and Async Keywords Within Catch and Finally Block in C# 6.0

Introduction

Traditionally await and asynch have been used in threading and multithreading programming. Until C# version 5.0 we used try, catch and finally together but await and asynch was not used with catch and finally. Now the latest released by Microsoft enables the programmer to use await and asynch in the catch block and in the finally block as well.

Working of try , catch and finally blocks is given below:

This section can be understood by analyzing a simple code in which an error is generated by the compiler handled by the try and catch block.

trycatch exception

Now in the code above we can see that the code above throws an exception of the type "DivideByZeroException" .
 
Now the the following code uses a try, catch and finally block to handle an exception generated by the code above and now it can be understood using the code shown below. 

  1. namespace ConsoleApplication4  
  2.   
  3. {  
  4.     class Example  
  5.     {  
  6.         static int z;  
  7.         public static void Main(String[] args)  
  8.         {  
  9.             int a = 10;  
  10.             int b = 0;  
  11.             try  
  12.             {  
  13.                 z = a / b;  
  14.             }  
  15.             catch (Exception e)  
  16.             {  
  17.                 Console.WriteLine("the value of z is " + z);  
  18.             }  
  19.             finally  
  20.             {  
  21.                 Console.WriteLine("above the value of z printed is its default value");  
  22.             }  
  23.    
  24.             System.Console.ReadKey();  
  25.         }  
  26.     }  
  27. }  
output


await and async keywords

These keywords simplify the code necessary to make asynchronous calls. Within the mechanization the compiler manages the complexity whilst the code remains relatively simple. A programmer might get the benefits of this new functionality merely by marking methods using the new keyword "async". These two were introduced first in C# version 5.0 and now the functionality has been enhanced in the new version 6.0 of the C# language.

The async keyword marks a method for the compiler. The await keyword signals the code to wait for the return of a long-running operation.

Async calls return  immediately, leaving the main thread responsive while the longer running process is forced to run in the background. Use of void returning methods is suitable only for specific situations in which the actions completed by the thread are no longer a concern of the main thread.

"void" returning methods are suitable for the launch and forget about it sort of scenario. Methods returning Task are similar to void in as much as those methods do not return a value to the calling method either. If data is to be returned to the main thread and handled there, one should use a return type of Task<T>.

Error handling within methods using the three return types is also different. Similarly, Task return type methods should also handle their own errors. Error handling now becomes more suitable and reliable for methods returning Task<T> might be accomplished within the calling thread.

The following is a program to illustrate the use of the await and async keywords within the catch block.

program.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Diagnostics;  
  6. using System.Drawing;  
  7. using System.Linq;  
  8. using System.Text;  
  9. using System.Threading.Tasks;  
  10. using System.Windows.Forms;  
  11.   
  12. namespace WindowsFormsApplication2  
  13. {  
  14.     public partial class Form1 : Form  
  15.     {  
  16.         public Form1()  
  17.         {  
  18.             InitializeComponent();  
  19.         }  
  20.   
  21.         private async void button1_Click(object sender, EventArgs e)  
  22.         {   
  23.             Task<string> theTask = DelayAsync();  
  24.   
  25.             try  
  26.             {  
  27.                 string result = await theTask;  
  28.                 Debug.WriteLine("Result: " + result);  
  29.             }  
  30.             catch (Exception ex)  
  31.             {  
  32.                 Debug.WriteLine("Exception Message: " + ex.Message);  
  33.                 label1.Text = "Exception Message: " + ex.Message;  
  34.             }  
  35.             Debug.WriteLine("Task IsCanceled: " + theTask.IsCanceled);  
  36.             Debug.WriteLine("Task IsFaulted:  " + theTask.IsFaulted);  
  37.             if (theTask.Exception != null)  
  38.             {  
  39.                 Debug.WriteLine("Task Exception Message: "  
  40.                     + theTask.Exception.Message);  
  41.                 Debug.WriteLine("Task Inner Exception Message: "  
  42.                     + theTask.Exception.InnerException.Message);  
  43.             }    
  44.         }//  
  45.   
  46.         private async Task<string> DelayAsync()  
  47.         {  
  48.             await Task.Delay(100);  
  49.   
  50.              
program.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using System.Windows.Forms;  
  6.   
  7. namespace WindowsFormsApplication1  
  8. {  
  9.     static class Program  
  10.     {  
  11.         /// <summary>  
  12.         /// The main entry point for the application.  
  13.         /// </summary>  
  14.         [STAThread]  
  15.         static void Main()  
  16.         {  
  17.             Application.EnableVisualStyles();  
  18.             Application.SetCompatibleTextRenderingDefault(false);  
  19.             Application.Run(new Form1());  
  20.         }  
  21.     }  
  22. }  
Output

button

 After clicking the button we will get the error message after the exception is caught.

output button

Summary

In this article we learned how to use the async and await keywords with the catch and finally blocks. These are the most convenient way to use these keywords that really helps programmers. Although these things remains simple and of course the complexity is removed by Microsoft.


Recommended Free Ebook
Similar Articles