Make multiple async HTTP requests with a single ca

2019-09-12 08:46发布

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?

1条回答
成全新的幸福
2楼-- · 2019-09-12 09:05

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.

查看更多
登录 后发表回答