using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net.NetworkInformation;
private static int failed = 0;
public static void Main()
private static void WaitForTaskWithTimeout()
Task taskA = Task.Run(() => DoComputation());
Console.WriteLine("The timeout interval elapsed");
private static void DoComputation()
Random rnd = new Random();
for (int i = 1; i <= 5000000; i++) {
int number = rnd.Next(0, 101);
Console.WriteLine("Total: {0:N0}", sum);
private static Action<Object> PrintThreadInfo = (object input) => {
throw new InvalidOperationException("Simulated Exception");
Console.WriteLine($"Task Id: {Task.CurrentId}, Input: {i}, TickCount: {Environment.TickCount}, ThreadId: {Thread.CurrentThread.ManagedThreadId}");
private static void WaitAllForTasks()
var tasks = new List<Task>();
for(int i = 0; i < 10; i++)
tasks.Add(Task.Factory.StartNew(PrintThreadInfo, i));
Task.WaitAll(tasks.ToArray());
catch(AggregateException e)
for(int j = 0; j < e.InnerExceptions.Count; j++)
Console.WriteLine(e.InnerExceptions[j].Message);
private static void WaitForAnyTask()
Task[] tasks = new Task[5];
for (int i = 0; i <= 4; i++) {
tasks[i] = Task.Run(() => Thread.Sleep(factor * 250 + 50));
int index = Task.WaitAny(tasks);
Console.WriteLine("Wait ended because task #{0} completed.", tasks[index].Id);
Console.WriteLine("Current Status of Tasks:");
Console.WriteLine("Task {0}: {1}", t.Id, t.Status);
private static void WhenAllForTasks()
List<Task> tasks = PingWebsites();
Task t = Task.WhenAll(tasks);
if(t.Status == TaskStatus.RanToCompletion)
Console.WriteLine("All tasks completed");
Console.WriteLine("{0} tasks failed", failed);
private static void WhenAnyForTasks()
List<Task> tasks = PingWebsites();
Task t = Task.WhenAny(tasks);
if(t.Status == TaskStatus.RanToCompletion)
Console.WriteLine("Any task completed");
Console.WriteLine("{0} tasks failed", failed);
private static List<Task> PingWebsites()
string[] urls = {"www.websitenotfound1.com", "www.websitenotfound2.com", "www.google.com"};
var tasks = new List<Task>();
tasks.Add(Task.Run(() => {
var reply = ping.Send(url);
if(reply.Status != IPStatus.Success)
Interlocked.Increment(ref failed);
throw new TimeoutException($"Unable to reach {url}");
Console.WriteLine($"Url {url}, Thread Id: {Thread.CurrentThread.ManagedThreadId}, Status: {e.Message}");
Interlocked.Increment(ref failed);