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 函数并分别处理它们
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
