parallel http requests in csharp

To perform parallel HTTP requests in C#, you can use the HttpClient class along with asynchronous programming constructs like async/await. You can initiate multiple requests and await their responses asynchronously, using Tasks and the Task.WhenAll method to parallelize the requests. Here is sample code that shows how to perform parallel HTTP GET requests using HttpClient:

main.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var urls = new List<string>
        {
            "https://www.google.com",
            "https://www.microsoft.com",
            "https://www.github.com"
        };

        var httpClient = new HttpClient();
        var tasks = urls.Select(url => httpClient.GetStringAsync(url)).ToList();

        var responses = await Task.WhenAll(tasks);

        foreach (var response in responses)
        {
            Console.WriteLine($"Response: {response.Substring(0, 50)}...");
        }
    }
}
684 chars
29 lines

In this sample code, we create a list of URLs to fetch data from, then create an instance of HttpClient to perform the actual HTTP requests. We then create a list of Task<string> objects that will each perform an asynchronous HTTP GET operation using httpClient.GetStringAsync(url).

Finally, we use Task.WhenAll to await all the tasks to complete and obtain the responses in an array of strings representing the HTTP response content.

gistlibby LogSnag