C#8理解中使用语法

问题描述 投票:0回答:2

我有下一个方法:

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;
}

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

但是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;
}

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

c# async-await resharper using
2个回答
3
投票

类似于using (...)使用IDispose清理资源,await using (...)使用IAsyncDisposable。这还允许在清理时执行耗时的任务(例如,涉及I / O)。


3
投票

如果SqlConnection实现了IAsyncDisposable接口,Resharper建议您切换到await using以使用DisposeAsync方法异步处理它

public interface IAsyncDisposable
{
    ValueTask DisposeAsync();
}
© www.soinside.com 2019 - 2024. All rights reserved.