C# 8 understanding await using syntax

C#Async AwaitResharperUsingC# 8.0

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

Similar as using (...) uses IDisposable 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.

Solution 2 - C#

If SqlConnection implements IAsyncDisposable interface, Resharper suggests you to switch to await using to dispose it asynchronously using DisposeAsync method

public interface IAsyncDisposable
{
    ValueTask DisposeAsync();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUriilView Question on Stackoverflow
Solution 1 - C#Klaus GütterView Answer on Stackoverflow
Solution 2 - C#Pavel AnikhouskiView Answer on Stackoverflow