.net - 如何做Task.ContinueWith(...)
问题描述
我使用 HttpClient,我想写这样的东西:
HttpClient client = ...;
Task<string> getContent()
{
return client.GetAsync(...)
.ContinueWith( t => t.Result.Content.ReadAsStringAsync() );
}
我知道我会写
.ContinueWith( t => t.Result.Content.ReadAsStringAsync().Result);
但池的线程之一将被阻止。我想要 continueWithTask 就像在Google Task library中一样。
我怎样才能实现它?
更新
是的,我确实需要使用任务而不是异步/等待,我真的知道我想要什么。
更新2
我修改了我的观点,现在我认为我选择技术是错误的。如果有人怀疑,这里有一个很好的代码示例。
解决方案
这些天你应该避免ContinueWith
,宁愿async
/await
除非你有非常非常具体的原因;我怀疑这会起作用:
async Task<string> getContent()
{
var foo = await client.GetAsync(...); // possibly with .ConfigureAwait(false)
return await foo.Content.ReadAsStringAsync(); // possibly with .ConfigureAwait(false)
}
推荐阅读
- laravel - 从 Laravel Forge/Digital Ocean 中检索网站文件
- swift - Swift:当应用程序处于前台和后台时,将图像临时存储在本地
- reactjs - 覆盖 antd 表格左上角的单元格
- java - 在scala中获取持续时间
- python - 如何在 C++ 中包含多语言开发头文件
- microsoft-teams - Microsoft.graph.teams:无法处理附件中的内容
- java - 运行 Java 小程序
- regex - 如何执行正则表达式以选择以特定字符串开头的每行的所有特定字符
- mysql - 为什么 SQL UNION 可以组合 MySQL 中具有不同数据类型的两列?
- c# - 为什么我的winform可以跨线程访问无错误无异常