137

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?

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
Uriil
  • 11,948
  • 11
  • 47
  • 68

2 Answers2

205

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.

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
  • 1
    what is the consequence of using `using` when I could use `await using`? – Overlord Zurg Apr 21 '23 at 14:55
  • 2
    `using` will call `Dispose()` rather than `await DisposeAsync()` and therefore unneccesarily block the current thread for some time. It depends on the type of object how undesirable the difference is. – Klaus Gütter Apr 22 '23 at 05:38
33

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();
}
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66