Using await operator in catch and finally blocks
Finally, in C# 6.0, you can now use the await
keyword in the catch
and finally
blocks. Previously, developers had to resort to all sorts of strange workarounds to achieve what is now easily achievable in C# 6.0. There really is not much more to it than the following.
Getting ready
We will create another class that will simulate the deletion of a file. An exception is thrown, and the catch
block is then executed along with the finally
statement. In both the catch
and finally
clauses, we will delay and await a task for 3 seconds. Then, we will output this delay to the console application window.
How to do it…
- Create a class called
Recipe9AwaitInCatchFinally
and add a method calledFileRunAsync()
to the class with the following code. Make sure that the file does not exist in the path given to thefilePath
variable:public static class Recipe9AwaitInCatchFinally { public static void FileRunAsync() { string filePath = @"c:\temp\XmlFile.xml"; RemoveFileAcync(filePath); ReadLine(); } }
- Then, add another method called
RemoveFileAcync()
to the class that takes a file path as a parameter. Includetry
catch
in this method and add the code that will attempt to read the file at the path supplied:public static async void RemoveFileAcync(string filepath) { try { WriteLine("Read file"); File.ReadAllLines(filepath); } catch (Exception ex) { } finally { } }
- In the
catch
clause, add the following code to simulate a process that takes a few seconds to complete:WriteLine($"Exception - wait 3 seconds {DateTime.Now.ToString("hh:MM:ss tt")}"); await Task.Delay(3000); WriteLine($"Exception - Print {DateTime.Now.ToString("hh:MM:ss tt")}"); WriteLine(ex.Message);
- In the
finally
clause, add another delay that simulates a task which also takes a few seconds to complete:WriteLine($"Finally - wait 3 seconds {DateTime.Now.ToString("hh:MM:ss tt")}"); await Task.Delay(3000); WriteLine($"Finally - completed {DateTime.Now.ToString("hh:MM:ss tt")}");
- In the console application, simply add a call to the
FileRunAsync()
method in theRecipe9AwaitInCatchFinally
class:Chapter1.Recipe9AwaitInCatchFinally.FileRunAsync();
How it works…
After adding the code, run the console application and have a look at the output:
You will notice that the exception thrown was a "file not found" exception. In catch
, the code stopped for 3 seconds while the task was delayed. The same is evident for the code in the finally
clause. It too was delayed for 3 seconds while the task was delayed.
This means that now, in your C# 6.0 applications, you can, for example, await in the catch
clause while an exception log message is written to the log. You can do the same thing in the finally
clause while closing database connections to dispose of other objects.
The process of how the compiler does this is rather complicated. You, however, don't need to worry about how this functionality is achieved. All you need to do is know that the await
keyword is now available to you as a developer for use in the catch
and finally
blocks.
Tip
Detailed steps to download the code bundle are mentioned in the Preface of this book. Please have a look. The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/CSharp-Programming-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!