Await in Catch and Finally Block in C# 6.0

In C# 5.0 Microsoft introduced asynchronous programming using the async and await keywords, but there was significant restriction for using await in catch and finally blocks. This was due to some specific issues in the compiler and with C# 6.0 they code in the compiler has undergone some changes to make it work. This was one of the most requested features from the developers worldwide because they resorted to write some complex logic in the catch block to overcome this restriction

Let’s take an example, in the earlier version if we write the code given below, we will get an compile error.

As you can see in the output window an compile error has occurred due to the use of awaited operation in the catch block. One typical example of this scenario is when we try to write the log using an asynchronous operation. In the code we have method for logging which the developer has made asynchronous by following the convention ending the name with async and is returning a Task. So to avoid the error we were following either to make it synchronous or will fire the method and doesn’t worry about the completion of the execution of that method.

In C# 6.0, it’s possible now to await the code in the catch and finally block and above code can be rewritten as follows there by avoiding the blocking of resources


No Comments

Add a Comment