Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
C# Programming Cookbook

You're reading from   C# Programming Cookbook Quick fixes to your common C# programming problems, with a focus on C# 6.0

Arrow left icon
Product type Paperback
Published in Jul 2016
Publisher Packt
ISBN-13 9781786467300
Length 476 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Dirk Strauss Dirk Strauss
Author Profile Icon Dirk Strauss
Dirk Strauss
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. New Features in C# 6.0 FREE CHAPTER 2. Classes and Generics 3. Object-Oriented Programming in C# 4. Composing Event-Based Programs Using Reactive Extensions 5. Create Microservices on Azure Service Fabric 6. Making Apps Responsive with Asynchronous Programming 7. High Performance Programming Using Parallel and Multithreading in C# 8. Code Contracts 9. Regular Expressions 10. Choosing and Using a Source Control Strategy 11. Creating a Mobile Application in Visual Studio 12. Writing Secure Code and Debugging in Visual Studio 13. Creating a Web Application in Azure 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:

How it works…

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!

You have been reading a chapter from
C# Programming Cookbook
Published in: Jul 2016
Publisher: Packt
ISBN-13: 9781786467300
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime