How do you run multiple HttpClient.GetAsync() requests at HttpClient.GetAsync() and process them each as soon as their responses are returned? At first I tried:
var response1 = await client.GetAsync("http://example.com/"); var response2 = await client.GetAsync("http://stackoverflow.com/"); HandleExample(response1); HandleStackoverflow(response2);
But of course, he is still consistent. So, I tried to run 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 start simultaneously, which is good, but, of course, the code should still wait one after another.
I want to be able to process the answer "example.com" as soon as it appears, and the answer "stackoverflow.com" as soon as it appears.
I could put two tasks in the array to use Task.WaitAny() in a loop, check which one is finished, and call the appropriate handler, but then ... how is it better than regular regular callbacks? Or is this not really the intended use case for async / wait? If not, how to use HttpClient.GetAsync() with callbacks?
To clarify - the behavior I need is something like this pseudo code:
client.GetAsyncWithCallback("http://example.com/", HandleExample); client.GetAsyncWithCallback("http://stackoverflow.com/", HandleStackoverflow);
Ben hoyt
source share