// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace E { public class Program { private static string Any(int secs) { Thread.Sleep(secs * 1000); return Thread.CurrentThread.ManagedThreadId.ToString(); } public static string One() { return Any(1); } public static string Two() { return Any(2); } public static string Three() { return Any(3); } public static void Test123() { Stopwatch sw = new Stopwatch(); sw.Start(); Task one = Task.Factory.StartNew(() => One()); Task two = Task.Factory.StartNew(() => Two()); Task three = Task.Factory.StartNew(() => Three()); string oneres = one.Result; Console.WriteLine("One result in {0} ms in thread {1}", sw.ElapsedMilliseconds, oneres); string twores = two.Result; Console.WriteLine("Two result in {0} ms in thread {1}", sw.ElapsedMilliseconds, twores); string threeres = three.Result; Console.WriteLine("Three result in {0} ms in thread {1}", sw.ElapsedMilliseconds, threeres); Console.WriteLine("All result in {0} ms", sw.ElapsedMilliseconds); } public static void Test321() { Stopwatch sw = new Stopwatch(); sw.Start(); Task one = Task.Factory.StartNew(() => One()); Task two = Task.Factory.StartNew(() => Two()); Task three = Task.Factory.StartNew(() => Three()); string threeres = three.Result; Console.WriteLine("Three result in {0} ms in thread {1}", sw.ElapsedMilliseconds, threeres); string twores = two.Result; Console.WriteLine("Two result in {0} ms in thread {1}", sw.ElapsedMilliseconds, twores); string oneres = one.Result; Console.WriteLine("One result in {0} ms in thread {1}", sw.ElapsedMilliseconds, oneres); Console.WriteLine("All result in {0} ms", sw.ElapsedMilliseconds); } public static void Test213() { Stopwatch sw = new Stopwatch(); sw.Start(); Task one = Task.Factory.StartNew(() => One()); Task two = Task.Factory.StartNew(() => Two()); Task three = Task.Factory.StartNew(() => Three()); string twores = two.Result; Console.WriteLine("Two result in {0} ms in thread {1}", sw.ElapsedMilliseconds, twores); string oneres = one.Result; Console.WriteLine("One result in {0} ms in thread {1}", sw.ElapsedMilliseconds, oneres); string threeres = three.Result; Console.WriteLine("Three result in {0} ms in thread {1}", sw.ElapsedMilliseconds, threeres); Console.WriteLine("All result in {0} ms", sw.ElapsedMilliseconds); } public static void Main(string[] args) { Test123(); Test321(); Test213(); } } }