Chain Tasks Together - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Task

Description

Chain Tasks Together

Demo Code


using System;/* ww  w.  j av  a2  s.  c  o  m*/
using System.Threading.Tasks;

class MainClass
    {
        static void Main(string[] args)
        {
            Task<int> firstTask = new Task<int>(() => sumAndPrintNumbers(100));
            Task secondTask = firstTask.ContinueWith(parent => printTotal(parent));
            Task thirdTask = secondTask.ContinueWith(parent => printMessage());

            firstTask.Start();

            Console.WriteLine("Press enter to finish");
            Console.ReadLine();
        }

        static int sumAndPrintNumbers(int baseNumber)
        {
            Console.WriteLine("sum&print called for {0}", baseNumber);
            int total = 0;
            for (int i = baseNumber, j = baseNumber + 10; i < j; i++)
            {
                Console.WriteLine("Number: {0}", i);
                total += i;
            }
            return total;
        }

        static void printTotal(Task<int> parentTask)
        {
            Console.WriteLine("Total is {0}", parentTask.Result);
        }

        static void printMessage()
        {
            Console.WriteLine("Message from third task");
        }
    }

Result


Related Tutorials