c# - 消除异步和等待流程
问题描述
在关于省略 async await的文章中,有一个例子如下:
public Task<string> GetElidingKeywordsAsync(string url)
{
using (var client = new HttpClient())
return client.GetStringAsync(url);
}
他将流程描述如下:
使用 GetElidingKeywordsAsync,代码执行以下操作:
创建 HttpClient 对象。
调用 GetStringAsync,它返回一个不完整的任务。
释放 HttpClient 对象。
返回从 GetStringAsync 返回的任务。
为什么流程不如下?
创建 HttpClient 对象。
释放 HttpClient 对象。
调用 GetStringAsync,并返回从 GetStringAsync 返回的任务。
解决方案
没有花括号或分号的 using 块有一个隐含的主体:
public Task<string> GetElidingKeywordsAsync(string url)
{
using (var client = new HttpClient())
return client.GetStringAsync(url); // using body
}
这可以归一化为:
public Task<string> GetElidingKeywordsAsync(string url)
{
using (var client = new HttpClient())
{
return client.GetStringAsync(url);
}
}
或者用 C#8.0 更紧凑地编写:
public Task<string> GetElidingKeywordsAsync(string url)
{
using var client = new HttpClient();
return client.GetStringAsync(url);
}
如果添加分号,则会出现一个空正文,从而产生您在 OP 中描述的行为:
public Task<string> GetElidingKeywordsAsync(string url)
{
HttpClient client;
using (client = new HttpClient()); // gets disposed before next statement
return client.GetStringAsync(url); // don't be fooled by the indent
}
这可以归一化为:
public Task<string> GetElidingKeywordsAsync(string url)
{
HttpClient client;
using (client = new HttpClient())
{
}
return client.GetStringAsync(url);
}
推荐阅读
- c# - 使用没有分离服务和存储库的 CQRS 真的会影响代码质量吗?
- c - 为什么我插入第一个元素后我的程序会终止?
- annotations - Squash Lombok 注释
- r - 将阶乘 ANOVA 事后比较的 p 值添加到 ggplot
- javascript - 选择“class1”的所有元素,直到到达具有类“should_stop_here is meet”的元素
- amazon-web-services - 您如何为 AWS 中的 lambda 遇到的错误百分比设置警报?
- java - 如何使用 JMF 录制音频设备?
- macos - Flutter 运行命令在我的 Mac 上不起作用
- c - 在枚举数据类型的情况下,是否有任何可能的方法来获取用户输入
- mongodb - 如何在 MongoDB 中存储结构私有字段?