using System; using System.Windows.Forms; public delegate void ShowValue(); public class Name { private string instanceName; public Name(string name) { this.instanceName = name; } public void DisplayToConsole() { Console.WriteLine(this.instanceName); } public void DisplayToWindow() { MessageBox.Show(this.instanceName); } } public class testTestDelegate { public static void Main() { Name testName = new Name("Koani"); ShowValue showMethod = testName.DisplayToWindow; showMethod(); } }
using System; using System.Windows.Forms; public class Name { private string instanceName; public Name(string name) { this.instanceName = name; } public void DisplayToConsole() { Console.WriteLine(this.instanceName); } public void DisplayToWindow() { MessageBox.Show(this.instanceName); } } public class testTestDelegate { public static void Main() { Name testName = new Name("Koani"); Action showMethod = testName.DisplayToWindow; showMethod(); } }
using System; using System.Threading; using System.Threading.Tasks; class StartNewDemo { static void Main() { Action<object> action = (object obj) => { Console.WriteLine("Task={0}, obj={1}, Thread={2}", Task.CurrentId, obj.ToString(), Thread.CurrentThread.ManagedThreadId); }; // Construct an unstarted task Task t1 = new Task(action, "alpha"); // Cosntruct a started task Task t2 = Task.Factory.StartNew(action, "beta"); // Block the main thread to demonstate that t2 is executing t2.Wait(); // Launch t1 t1.Start(); Console.WriteLine("t1 has been launched. (Main Thread={0})", Thread.CurrentThread.ManagedThreadId); // Wait for the task to finish. // You may optionally provide a timeout interval or a cancellation token // to mitigate situations when the task takes too long to finish. t1.Wait(); // Construct an unstarted task Task t3 = new Task(action, "gamma"); // Run it synchronously t3.RunSynchronously(); // Although the task was run synchrounously, it is a good practice to wait for it which observes for // exceptions potentially thrown by that task. t3.Wait(); Console.ReadKey(); } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; // Demonstrates how to associate state with task continuations. class ContinuationState { // Simluates a lengthy operation and returns the time at which // the operation completed. public static DateTime DoWork() { // Simulate work by suspending the current thread // for two seconds. Console.WriteLine("Thread = {0} sleep 2 seconds", Task.CurrentId); Thread.Sleep(2000); // Return the current time. return DateTime.Now; } static void Main(string[] args) { Action action = () => { DoWork(); }; Task<DateTime> t = new Task<DateTime>(DoWork); t.Start(); Console.WriteLine("Date = {0}", t.Result); t.Wait(); Console.ReadKey(); } }
using System; using System.Threading; using System.Threading.Tasks; namespace Thread_Task_Sample_Exception_Simple { class Program { static void Main(string[] args) { Action<object> action = (object obj) => { Console.WriteLine("Task={0}, obj={1}, Thread={2} Throw Exception", Task.CurrentId, obj.ToString(), Thread.CurrentThread.ManagedThreadId); throw (new Exception()); }; // Cosntruct a started task Task t = Task.Factory.StartNew(action, "A"); for (int i = 0; i < 50; i++) { Console.Write("."); Thread.Sleep(200); } Console.WriteLine(); try { // Block the main thread to demonstate that t2 is executing t.Wait(); } catch (Exception ex) { Console.WriteLine("Task.Wait cause an exception, We caught it"); } Console.ReadKey(); } } }
using System; using System.Threading; using System.Threading.Tasks; class ContinuationSimpleDemo { // Demonstrated features: // Task.Factory // Task.ContinueWith() // Task.Wait() // Expected results: // A sequence of three unrelated tasks is created and executed in this order - alpha, beta, gamma. // A sequence of three related tasks is created - each task negates its argument and passes is to the next task: 5, -5, 5 is printed. // A sequence of three unrelated tasks is created where tasks have different types. // Documentation: static void Main() { Action<string> action = (str) => Console.WriteLine("Task={0}, str={1}, Thread={2}", Task.CurrentId, str, Thread.CurrentThread.ManagedThreadId); // Creating a sequence of action tasks (that return no result). Console.WriteLine("Creating a sequence of action tasks (that return no result)"); Task.Factory.StartNew(() => action("alpha")) .ContinueWith(antecendent => action("beta")) // Antecedent data is ignored .ContinueWith(antecendent => action("gamma")) .Wait(); Func<int, int> negate = (n) => { Console.WriteLine("Task={0}, n={1}, -n={2}, Thread={3}", Task.CurrentId, n, -n, Thread.CurrentThread.ManagedThreadId); return -n; }; // Creating a sequence of function tasks where each continuation uses the result from its antecendent Console.WriteLine("\nCreating a sequence of function tasks where each continuation uses the result from its antecendent"); Task<int>.Factory.StartNew(() => negate(5)) .ContinueWith(antecendent => negate(antecendent.Result)) // Antecedent result feeds into continuation .ContinueWith(antecendent => negate(antecendent.Result)) .Wait(); // Creating a sequence of tasks where you can mix and match the types Console.WriteLine("\nCreating a sequence of tasks where you can mix and match the types"); Task<int>.Factory.StartNew(() => negate(6)) .ContinueWith(antecendent => action("x")) .ContinueWith(antecendent => negate(7)) .Wait(); Console.ReadKey(); } }
using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; public class Example { public static void Main() { var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; // Store references to the tasks so that we can wait on them and // observe their status after cancellation. Task t; var tasks = new ConcurrentBag<Task>(); Console.WriteLine("Press any key to begin tasks..."); Console.WriteLine("To terminate the example, press 'c' to cancel and exit..."); Console.ReadKey(); Console.WriteLine(); // Request cancellation of a single task when the token source is canceled. // Pass the token to the user delegate, and also to the task so it can // handle the exception correctly. t = Task.Factory.StartNew(() => DoSomeWork(1, token), token); Console.WriteLine("Task {0} executing", t.Id); tasks.Add(t); // Request cancellation of a task and its children. Note the token is passed // to (1) the user delegate and (2) as the second argument to StartNew, so // that the task instance can correctly handle the OperationCanceledException. t = Task.Factory.StartNew(() => { // Create some cancelable child tasks. Task tc; for (int i = 3; i <= 10; i++) { // For each child task, pass the same token // to each user delegate and to StartNew. tc = Task.Factory.StartNew(iteration => DoSomeWork((int)iteration, token), i, token); Console.WriteLine("Task {0} executing", tc.Id); tasks.Add(tc); // Pass the same token again to do work on the parent task. // All will be signaled by the call to tokenSource.Cancel below. DoSomeWork(2, token); } }, token); Console.WriteLine("Task {0} executing", t.Id); tasks.Add(t); // Request cancellation from the UI thread. if (Console.ReadKey().KeyChar == 'c') { tokenSource.Cancel(); Console.WriteLine("\nTask cancellation requested."); // Optional: Observe the change in the Status property on the task. // It is not necessary to wait on tasks that have canceled. However, // if you do wait, you must enclose the call in a try-catch block to // catch the TaskCanceledExceptions that are thrown. If you do // not wait, no exception is thrown if the token that was passed to the // StartNew method is the same token that requested the cancellation. } try { Task.WaitAll(tasks.ToArray()); } catch (AggregateException e) { Console.WriteLine("\nAggregateException thrown with the following inner exceptions:"); // Display information about each exception. foreach (var v in e.InnerExceptions) { if (v is TaskCanceledException) Console.WriteLine(" TaskCanceledException: Task {0}", ((TaskCanceledException)v).Task.Id); else Console.WriteLine(" Exception: {0}", v.GetType().Name); } Console.WriteLine(); } // Display status of all tasks. foreach (var task in tasks) Console.WriteLine("Task {0} status is now {1}", task.Id, task.Status); Console.ReadKey(); } static void DoSomeWork(int taskNum, CancellationToken ct) { // Was cancellation already requested? if (ct.IsCancellationRequested == true) { Console.WriteLine("Task {0} was cancelled before it got started.", taskNum); ct.ThrowIfCancellationRequested(); } int maxIterations = 100; // NOTE!!! A "TaskCanceledException was unhandled // by user code" error will be raised here if "Just My Code" // is enabled on your computer. On Express editions JMC is // enabled and cannot be disabled. The exception is benign. // Just press F5 to continue executing your code. for (int i = 0; i <= maxIterations; i++) { // Do a bit of work. Not too much. var sw = new SpinWait(); for (int j = 0; j <= 100; j++) sw.SpinOnce(); if (ct.IsCancellationRequested) { Console.WriteLine("Task {0} cancelled", taskNum); ct.ThrowIfCancellationRequested(); } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Text; namespace Thread_Task_Sample_Parallel { class Program { static void Main(string[] args) { int[] data = new int[100]; int i = 0; for (i = 0; i < data.Length; i++) { data[i] = i; Console.Write("{0} ", data[i]); } Console.WriteLine(" \n "); Console.WriteLine("\nParallel running ... ... \n"); Parallel.For(0, 100, (j)=> { System.Threading.Thread.Sleep(1000); data[j] = data[j] * 2; Console.Write("{0} ", data[j]); }); Console.WriteLine("\n\nParallel end ... ... \n"); Console.WriteLine(" \n "); for (i = 0; i < data.Length; i++) { Console.Write("{0} ", data[i]); } Console.WriteLine(" \n "); Console.ReadKey(); } } }