1

I have a simple C# app which must send one HTTP GET request to many servers and get a response from each of them on button click. Also I need it to perform some operations after all servers responded. So, I can use HttpWebRequest class with async operations and count total responses number in every callback. But maybe there's a special library for advanced callback flow control, like Async in JavaScript for example?

JustLogin
  • 1,822
  • 5
  • 28
  • 50
  • There are too many ways to approach this problem. The answers would just turn into a straw-poll for which one people liked. The best thing is to do some research on the topic yourself, find two or three, _analyze_ them, determine if they work for you or not, and _try them out_. Come to us when you have a specific question about something you have attempted to do. – Blue Aug 13 '16 at 10:10
  • @FrankerZ I just need a simple callback library, which allows to have a single callback for multiple async operations. – JustLogin Aug 13 '16 at 10:11
  • Unfortunately, questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are also off-topic here. You may find better luck [SoftwareRecs.SE](//softwarerecs.stackexchange.com/tour). Remember to read [their question requirements](//softwarerecs.stackexchange.com/help/on-topic) as they are more strict than this site. – Blue Aug 13 '16 at 10:17

1 Answers1

3

You can call HttpWebRequest.GetResponseAsync to obtain Task<WebResponse>. Then call Task.WhenAll to get another task, which ends when all other tasks end. To wait synchronously for all tasks, use Task.WaitAll.

Example:

async void StartRequests()
{
    // start requests
    var responseTasks = requests
    .Select(
        r => HttpWebRequest.GetResponseAsync(r)
            // you can attach continuation to every task
            .ContinueWith(t => ProcessResult(t.Result)))
    .ToArray();
    // wait for all tasks to finish
    await Task.WhenAll(responseTasks);
    // ...
}

Useful links: Task Parallel Library, Asynchronous Programming with async and await

Also, I believe, System.Net.Http.HttpClient is a more convenient class for making HTTP calls.

just.ru
  • 648
  • 5
  • 12