WaitingForTasks

CSharp · Console

/Program.cs

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net.NetworkInformation;
					
public class Program
{
	private static int failed = 0;
	
	public static void Main()
	{
		//WaitForTaskWithTimeout();
		//WaitAllForTasks();
		//WaitForAnyTask();
		WhenAllForTasks();
		WhenAnyForTasks();
	}
	
	private static void WaitForTaskWithTimeout() 
	{
		Task taskA = Task.Run(() => DoComputation());
		// use < 50 for timeout interval
		if(!taskA.Wait(100))
			Console.WriteLine("The timeout interval elapsed");
	}
	
	private static void DoComputation()
	{
		Random rnd = new Random();
		long sum = 0;
		for (int i = 1; i <= 5000000; i++) {
			int number = rnd.Next(0, 101);
			sum += number;
		}
		Console.WriteLine("Total:   {0:N0}", sum);
	}
	
	private static Action<Object> PrintThreadInfo = (object input) => {
		int i = (int)input;
		if(i >= 2 && i <= 5)
		{
			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));
		}
		try 
		{
			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++) {
			int factor = 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:");
		foreach (var t in tasks)
			Console.WriteLine("Task {0}: {1}", t.Id, t.Status);
	}
	
	private static void WhenAllForTasks()
	{
		List<Task> tasks = PingWebsites();
		Task t = Task.WhenAll(tasks);
		try
		{
			t.Wait();
		}
		catch {}
		
		if(t.Status == TaskStatus.RanToCompletion)
			Console.WriteLine("All tasks completed");
		else
			Console.WriteLine("{0} tasks failed", failed);
	}
	
	private static void WhenAnyForTasks()
	{
		List<Task> tasks = PingWebsites();
		Task t = Task.WhenAny(tasks);
		try
		{
			t.Wait();
		}
		catch {}
		
		if(t.Status == TaskStatus.RanToCompletion)
			Console.WriteLine("Any task completed");
		else
			Console.WriteLine("{0} tasks failed", failed);
	}
	
	
	private static List<Task> PingWebsites() 
	{
		failed = 0;
		string[] urls = {"www.websitenotfound1.com", "www.websitenotfound2.com", "www.google.com"};
		var tasks  = new List<Task>();
		
		foreach(var url in urls) 
		{
			tasks.Add(Task.Run(() => {
				//Console.WriteLine($"Url {url}, Thread Id: {Thread.CurrentThread.ManagedThreadId}");
				var ping = new Ping();
				try
				{
					var reply = ping.Send(url);
					//Console.WriteLine($"Url {url}, Thread Id: {Thread.CurrentThread.ManagedThreadId}, Status: {reply.Status}");
					if(reply.Status != IPStatus.Success) 
					{
						
						Interlocked.Increment(ref failed);
						throw new TimeoutException($"Unable to reach {url}");
					}
				}
				catch(PingException e)
				{
					Console.WriteLine($"Url {url}, Thread Id: {Thread.CurrentThread.ManagedThreadId}, Status: {e.Message}");
					Interlocked.Increment(ref failed);
					throw;
				}
			}));		
		}
		
		return tasks;
	}
	
}
;