DEV Community

Cover image for C# - Parallel Programming with async and await for Concurrent Execution
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Parallel Programming with async and await for Concurrent Execution

C# provides asynchronous and parallel programming tools, making performing multiple tasks concurrently and efficiently easier. When working with tasks and async/await, you can use Task.WhenAll to execute multiple asynchronous operations concurrently and wait for all of them to complete.

Here's an example:

using System.Diagnostics;
public class Program
{
    public async static Task Main()
    {
        var stopwatch = new Stopwatch();
        stopwatch.Start();

        // Create multiple tasks to fetch web pages concurrently
        var task1 = FetchWebPageAsync("https://jsonplaceholder.typicode.com/todos/1");
        var task2 = FetchWebPageAsync("https://jsonplaceholder.typicode.com/todos/2");
        var task3 = FetchWebPageAsync("https://jsonplaceholder.typicode.com/todos/3");

        // Wait for all tasks to complete
        await Task.WhenAll(task1, task2, task3);

        stopwatch.Stop();
        Console.WriteLine($"Time elapsed: {stopwatch.ElapsedMilliseconds} ms");
    }

    public static async Task<string> FetchWebPageAsync(string url)
    {
        using var httpClient = new HttpClient();
        var response = await httpClient.GetAsync(url);
        return await response.Content.ReadAsStringAsync();
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we use HttpClient to fetch multiple web pages concurrently. By creating separate tasks for each page fetch operation and then using Task.WhenAll, we can efficiently fetch the pages in parallel.

This technique is particularly useful for scenarios like web scraping, where you must perform multiple I/O-bound operations concurrently without blocking the main thread.

Remember to be cautious when dealing with parallel programming, as it introduces concurrency concerns. You should handle exceptions and manage resources correctly. Additionally, be mindful of the degree of parallelism to avoid overwhelming the system with too many concurrent tasks.

Top comments (0)