How do I handle concurrency with async/await

Handling concurrency in C# using async and await is crucial for building efficient applications that maintain responsiveness. Below is an example demonstrating how to manage multiple asynchronous tasks concurrently.

// Example of concurrency using async and await in C# public async Task ProcessDataAsync() { // Start multiple tasks Task task1 = GetDataFromService1Async(); Task task2 = GetDataFromService2Async(); // Await their results string result1 = await task1; string result2 = await task2; // Process results Console.WriteLine($"Result from service 1: {result1}"); Console.WriteLine($"Result from service 2: {result2}"); } public async Task GetDataFromService1Async() { await Task.Delay(1000); // Simulate a delay return "Data from Service 1"; } public async Task GetDataFromService2Async() { await Task.Delay(1500); // Simulate a longer delay return "Data from Service 2"; }

C# async await concurrency Task async programming