C#:C# Async/Await and Task Concurrency (Task.WhenAll)
C#•Async & Concurrency

C# Async/Await and Task Concurrency (Task.WhenAll)

Learn the Task-based Asynchronous Pattern (TAP) in C#, writing non-blocking concurrent code.

Syntax

public async Task<int> FetchDataAsync() { await Task.Delay(100); return 42; }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
async TaskReturn TypeAsynchronous operation returning void or value.
awaitOperatorYields thread back to pool until task completes.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C# locally:

using System;
using System.Threading.Tasks;

public class Program {
    public static async Task<string> SimulateServiceCall(string serviceName, int delayMs) {
        Console.WriteLine($"[{serviceName}] Request initiated...");
        await Task.Delay(delayMs);
        return $"{serviceName}: Responded in {delayMs}ms";
    }

    public static async Task Main() {
        Console.WriteLine("--- Launching Parallel Async Requests ---");

        // Run requests concurrently with Task.WhenAll
        var task1 = SimulateServiceCall("AuthAPI", 40);
        var task2 = SimulateServiceCall("PaymentGateway", 25);
        var task3 = SimulateServiceCall("Inventory", 35);

        string[] results = await Task.WhenAll(task1, task2, task3);

        Console.WriteLine("\nResults Summary:");
        foreach (var res in results) {
            Console.WriteLine($"  -> {res}");
        }
    }
}
Expected Output:
--- Launching Parallel Async Requests ---
[AuthAPI] Request initiated...
[PaymentGateway] Request initiated...
[Inventory] Request initiated...

Results Summary:
  -> AuthAPI: Responded in 40ms
  -> PaymentGateway: Responded in 25ms
  -> Inventory: Responded in 35ms

How It Works: Step-by-Step

  • Lines 5-9: Defines async Task<string> method simulating network I/O with Task.Delay.
  • Lines 15-19: Launches 3 tasks concurrently and awaits completion with Task.WhenAll.

Key Concepts

  • await releases the current thread back to the .NET thread pool during I/O delays.
  • Task.WhenAll runs multiple tasks in parallel and bundles results.
  • Always return Task instead of void from async methods (except event handlers).

Common Mistake: Blocking async tasks using .Result or .Wait() instead of await

Using task.Result blocks the calling thread and can cause deadlocks. Always use await.

❌ Incorrect
string res = FetchDataAsync().Result; // Thread starvation / deadlock risk!
✅ Correct
string res = await FetchDataAsync(); // Non-blocking

Related C# Tutorials & Compiler

Run and test C# on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C# Online Compiler