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 函数并分别处理它们
基础教程推荐
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- 将数据集转换为列表 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 从 C# 控制相机设备 2022-01-01
