using System; using System.Collections.Generic; using System.Net.NetworkInformation; using System.Threading; using System.Threading.Tasks; public class Example { public static void Main() { int failed = 0; var tasks = new List<Task>(); String[] urls = { "www.adatum.com", "www.cohovineyard.com", "www.cohowinery.com", "www.northwindtraders.com", "www.contoso.com" }; foreach (var value in urls) { var url = value; tasks.Add(Task.Run( () => { var png = new Ping(); try { var reply = png.Send(url); if (! (reply.Status == IPStatus.Success)) { Interlocked.Increment(ref failed); throw new TimeoutException("Unable to reach " + url + "."); } } catch (PingException) { Interlocked.Increment(ref failed); throw; } })); } Task t = Task.WhenAll(tasks); try { t.Wait(); } catch {} if (t.Status == TaskStatus.RanToCompletion) Console.WriteLine("All ping attempts succeeded."); else if (t.Status == TaskStatus.Faulted) Console.WriteLine("{0} ping attempts failed", failed); } } // The example displays output like the following: // 5 ping attempts failed
private static async Task Main(string[] args) { var stopwatch = new Stopwatch(); stopwatch.Start(); // this task will take about 2.5s to complete var sumTask = SlowAndComplexSumAsync(); // this task will take about 4s to complete var wordTask = SlowAndComplexWordAsync(); // running them in parallel should take about 4s to complete await Task.WhenAll(sumTask, wordTask); // The elapsed time at this point will only be about 4s Console.WriteLine("Time elapsed when both complete..." + stopwatch.Elapsed); // These lines are to prove the outputs are as expected, // i.e. 300 for the complex sum and "ABC...XYZ" for the complex word Console.WriteLine("Result of complex sum = " + sumTask.Result); Console.WriteLine("Result of complex letter processing " + wordTask.Result); Console.Read(); }
References
https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.whenall?view=net-5.0
https://jeremylindsayni.wordpress.com/2019/03/11/using-async-await-and-task-whenall-to-improve-the-overall-speed-of-your-c-code/