Task Continuation C# with Example
using System; using System.Threading; using System.Threading.Tasks; namespace CSharpMultiThreading { class DemoTask { // A method to be run as a task. static void MyTask() { Console.WriteLine("MyTask() starting"); for(int count = 0; count < 5; count++) { Thread.Sleep(500); Console.WriteLine("In MyTask(), count is " + count); } Console.WriteLine("MyTask terminating"); } // A method to be run as a continuation. static void ContTask(Task t) { Console.WriteLine("Continuation starting"); for(int count = 0; count < 5; count++) { Thread.Sleep(500); Console.WriteLine("Continuation count is " + count ); } Console.WriteLine("Continuation terminating"); } static void Main() { Console.WriteLine("Main thread starting."); // Construct and Run a task. Task tsk = Task.Factory.StartNew(MyTask); Task taskCont = tsk.ContinueWith(ContTask); // Keep Main() alive until MyTask() finishes. tsk.Wait(); taskCont.Wait(); // Dispose all tasks. tsk.Dispose(); taskCont.Dispose(); Console.WriteLine("Main thread ending."); } } }