官术网_书友最值得收藏!

  • C# Programming Cookbook
  • Dirk Strauss
  • 531字
  • 2021-07-14 11:08:43

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…

  1. Create a class called Recipe9AwaitInCatchFinally and add a method called FileRunAsync() to the class with the following code. Make sure that the file does not exist in the path given to the filePath variable:
    public static class Recipe9AwaitInCatchFinally
    {
        public static void FileRunAsync()
        {
            string filePath = @"c:\temp\XmlFile.xml";
            RemoveFileAcync(filePath);
            ReadLine();
        }
    }
  2. Then, add another method called RemoveFileAcync() to the class that takes a file path as a parameter. Include try 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
        {        
    
        }
    }
  3. 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);
  4. 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")}");
  5. In the console application, simply add a call to the FileRunAsync() method in the Recipe9AwaitInCatchFinally 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!

主站蜘蛛池模板: 营山县| 白城市| 衡山县| 武穴市| 富民县| 佛教| 成安县| 磐石市| 延安市| 荆门市| 三门县| 溧水县| 余江县| 临汾市| 会宁县| 满洲里市| 赤峰市| 乡城县| 嵊州市| 东城区| 凭祥市| 乌兰察布市| 基隆市| 大埔区| 天台县| 海丰县| 永宁县| 台东县| 民和| 湖南省| 海城市| 海口市| 当雄县| 彩票| 尚义县| 运城市| 宁晋县| 五台县| 博兴县| 贵定县| 巧家县|