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 函数并分别处理它们
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01