Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

c# - Starting multiple async/await functions at once and handling them separately

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.

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.

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...