Await in catch and finally blocks in C# 6

This is the fifth part of a series of posts I’m making into Upcoming Language Feature Changes in C# 6.

This is definitely not syntactic sugar and if you’re doing any asynchronous programming you’ll be very pleased with this new feature.

    public async Task<int> CharacterCountAsync(string file)
    {
        int count = 0;

        try
        {
            using (var reader = new StringReader(file))
            {
                var contents = await reader.ReadToEndAsync();
                count = contents.Length;
            }
        }
        catch (Exception exc)
        {
            // C# 6 allows this
            await Logger.LogAsync(exc);
            throw;
        }
        finally
        {
            // C# 6 allows this
            await Logger.LogAsync("CharacterCountAsync Finished");
        }

        return count;
    }

I was toying with not posting about it as the name is very descriptive and the code is pretty self explanatory, so hopefully I haven’t missed anything!

Leave a Reply

Your email address will not be published. Required fields are marked *