Starting multiple async/await functions at once and handling them separately(一次启动多个 async/await 函数并分别处理它们)
问题描述
如何一次启动多个 HttpClient.GetAsync()
请求,并在它们各自的响应返回后立即处理它们?首先我尝试的是:
How do you start multiple HttpClient.GetAsync()
requests at once, and handle them each as soon as their respective responses come back? First what I tried is:
var response1 = await client.GetAsync("http://example.com/");
var response2 = await client.GetAsync("http://stackoverflow.com/");
HandleExample(response1);
HandleStackoverflow(response2);
当然,它仍然是连续的.所以我尝试同时启动它们:
But of course it's still sequential. So then I tried starting them both at once:
var task1 = client.GetAsync("http://example.com/");
var task2 = client.GetAsync("http://stackoverflow.com/");
HandleExample(await task1);
HandleStackoverflow(await task2);
现在任务同时启动了,这很好,当然代码还是要一个接一个地等待.
Now the tasks are started at the same time, which is good, but of course the code still has to wait for one after the other.
我想要的是能够在example.com"响应一进来就处理它,而stackoverflow.com"响应一进来就能够处理.
What I want is to be able to handle the "example.com" response as soon as it comes in, and the "stackoverflow.com" response as soon as it comes in.
我可以将这两个任务放在一个数组中,并在循环中使用 Task.WaitAny()
,检查哪一个完成并调用适当的处理程序,但是...只是常规的旧回调?或者这不是 async/await 的真正预期用例?如果没有,我将如何将 HttpClient.GetAsync()
与回调一起使用?
I could put the two tasks in an array an use Task.WaitAny()
in a loop, checking which one finished and call the appropriate handler, but then ... how is that better than just regular old callbacks? Or is this not really an intended use case for async/await? If not, how would I use HttpClient.GetAsync()
with callbacks?
澄清一下——我所追求的行为类似于这个伪代码:
To clarify -- the behaviour I'm after is something like this pseudo-code:
client.GetAsyncWithCallback("http://example.com/", HandleExample);
client.GetAsyncWithCallback("http://stackoverflow.com/", HandleStackoverflow);
推荐答案
你可以使用 ContinueWith
和 WhenAll
来等待一个新的Task
,task1 和 task2 将并行执行
You can use ContinueWith
and WhenAll
to await one new Task
, task1 and task2 will be executed in parallel
var task1 = client.GetAsync("http://example.com/")
.ContinueWith(t => HandleExample(t.Result));
var task2 = client.GetAsync("http://stackoverflow.com/")
.ContinueWith(t => HandleStackoverflow(t.Result));
var results = await Task.WhenAll(new[] { task1, task2 });
这篇关于一次启动多个 async/await 函数并分别处理它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:一次启动多个 async/await 函数并分别处理它们


基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30