C#8理解使用语法

Uri*_*iil 1 c# resharper using async-await

我有下一个方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

一切都很好,也很清楚,连接将放在示波器的末尾。

但是resharper建议将其更改为:

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;
}
Run Code Online (Sandbox Code Playgroud)

它在使用前增加了等待,并且代码已成功编译。这是什么意思,什么时候需要做?

Pav*_*ski 20

如果SqlConnection实现了IAsyncDisposable接口,Resharper建议你改用methodawait using异步配置DisposeAsync

public interface IAsyncDisposable
{
    ValueTask DisposeAsync();
}
Run Code Online (Sandbox Code Playgroud)


Kla*_*ter 7

类似using (...)用途IDispose清理资源,await using (...)采用IAsyncDisposable。这允许在清除时也执行费时的任务(例如,涉及I / O)而不会阻塞。

  • “using”将调用“Dispose()”而不是“await DisposeAsync()”,因此不必要地阻塞当前线程一段时间。这取决于对象的类型,这种差异有多不受欢迎。 (10认同)
  • 当我可以使用“await using”时,使用“using”会产生什么后果? (3认同)