一次启动多个 async/await 函数并分别处理它们 [英] Starting multiple async/await functions at once and handling them separately

查看:43
本文介绍了一次启动多个 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);

推荐答案

你可以使用 ContinueWithWhenAll 来等待一个新的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 函数并分别处理它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆