using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
public static async Task Main()
long startTime = Stopwatch.GetTimestamp();
var indexes = new List<int> { -2, -1, 0, 1, 2, 3 };
var tasks = indexes.Select(async key =>
Console.WriteLine($"Looping through Select()... key = {key}");
var result = await DoWorkAsync($"Task {key}", key);
Console.WriteLine("From try catch...");
Console.WriteLine(ex.Message);
Console.WriteLine("!!! Before calling WhenAll()... !!!\n");
await Task.WhenAll(tasks);
catch (OperationCanceledException)
Console.WriteLine("Cancelled");
catch (AggregateException aggregateException)
Console.WriteLine("2 or more exceptions were thrown");
catch (Exception exception)
Console.WriteLine($"A single exception was thrown: ${exception.Message}");
var elapsedTime = Stopwatch.GetElapsedTime(startTime);
Console.WriteLine($"Time taken: {elapsedTime.ToString(@"m\:ss\.fff")}");
Console.WriteLine("--- Successful results ---");
var successfulResults = tasks
.Where(t => t.IsCompletedSuccessfully)
Console.WriteLine(JsonSerializer.Serialize(successfulResults));
Console.WriteLine("Main ended");
public static async Task<int> DoWorkAsync(string nameOfTask, int secondsToDelay)
throw new Exception($"Seconds with value {secondsToDelay} to delay cannot less than 0.");
Console.WriteLine($"\n--- {nameOfTask} has started. ---");
await Task.Delay(secondsToDelay * 1000);
Console.WriteLine($"--- {nameOfTask} has finished. ---\n");
return secondsToDelay * 3;