C# 8 understanding await using syntax

Uriil picture Uriil · Nov 10, 2019 · Viewed 15.3k times · Source

I have next method:

public async Task<IEnumerable<Quote>> GetQuotesAsync()
{
    using var connection = new SqlConnection(_connectionString);

    var allQuotes = await connection.QueryAsync<Quote>(@"SELECT [Symbol], [Bid], [Ask], [Digits] FROM [QuoteEngine].[RealtimeData]");

    return allQuotes;
}

Everything fine and clear, connection will be disposed at the end of scope.

But resharper suggests to change it to:

public async Task<IEnumerable<Quote>> GetQuotesAsync()
{
    await using var connection = new SqlConnection(_connectionString);

    var allQuotes = await connection.QueryAsync<Quote>(@"SELECT [Symbol], [Bid], [Ask], [Digits] FROM [QuoteEngine].[RealtimeData]");

    return allQuotes;
}

It adds await before using and code is compiled successfully. What does it mean and when do we need to do that?

Answer

Klaus G&#252;tter picture Klaus Gütter · Nov 10, 2019

Similar as using (...) uses IDispose to clean up resources, await using (...) uses IAsyncDisposable. This allows to perform also time-consuming tasks (e.g involving I/O) on cleanup without blocking.