C#8理解等待使用语法 [英] C# 8 understanding await using syntax

查看:80
本文介绍了C#8理解等待使用语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个方法:

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.

但是resharper建议将其更改为:

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?

推荐答案

类似于使用(...)使用 IDispose 清理资源,等待使用(...)使用 IAsyncDisposable .这样一来,您就可以在清理过程中执行耗时的任务(例如,涉及I/O)而不会阻塞.

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.

这篇关于C#8理解等待使用语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆