首页 > 解决方案 > 如何做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

我修改了我的观点,现在我认为我选择技术是错误的。如果有人怀疑,这里有一个很好的代码示例

标签: .nettask-parallel-library

解决方案


这些天你应该避免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)
}

推荐阅读