Book Image

C# Programming Cookbook

By : Dirk Strauss
Book Image

C# Programming Cookbook

By: Dirk Strauss

Overview of this book

During your application development workflow, there is always a moment when you need to get out of a tight spot. Through a recipe-based approach, this book will help you overcome common programming problems and get your applications ready to face the modern world. We start with C# 6, giving you hands-on experience with the new language features. Next, we work through the tasks that you perform on a daily basis such as working with strings, generics, and lots more. Gradually, we move on to more advanced topics such as the concept of object-oriented programming, asynchronous programming, reactive extensions, and code contracts. You will learn responsive high performance programming in C# and how to create applications with Azure. Next, we will review the choices available when choosing a source control solution. At the end of the book, we will show you how to create secure and robust code, and will help you ramp up your skills when using the new version of C# 6 and Visual Studio
Table of Contents (21 chapters)
C# Programming Cookbook
Credits
About the Author
Acknowledgements
About the Reviewer
www.PacktPub.com
Preface
Index

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!