Wait for Tasks to Complete - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Task

Description

Wait for Tasks to Complete

Demo Code


using System;/* w  ww.j  a v  a 2 s  .c  o m*/
using System.Threading;
using System.Threading.Tasks;

class MainClass
    {
        static void Main(string[] args)
        {
            Task<int> task1 = Task<int>.Factory.StartNew(() => writeDays());
            Task<int> task2 = Task<int>.Factory.StartNew(() => writeMonths());
            Task<int> task3 = Task<int>.Factory.StartNew(() => writeCities());

            Task.WaitAll(task1, task2, task3);

            Console.WriteLine("{0} days were written", task1.Result);
            Console.WriteLine("{0} months were written", task2.Result);
            Console.WriteLine("{0} cities were written", task3.Result);

            Console.WriteLine("Press Enter to exit");
            Console.ReadLine();
        }

        static int writeDays()
        {
            string[] daysArray = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
            foreach (string day in daysArray)
            {
                Console.WriteLine("Day of the Week: {0}", day);
                Thread.Sleep(500);
            }
            return daysArray.Length;
        }

        static int writeMonths()
        {
            string[] monthsArray = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
            foreach (string month in monthsArray)
            {
                Console.WriteLine("Month: {0}", month);
                Thread.Sleep(500);
            }
            return monthsArray.Length;
        }

        static int writeCities()
        {
            string[] citiesArray = { "London", "New York", "Paris", "Tokyo", "Sydney" };
            foreach (string city in citiesArray)
            {
                Console.WriteLine("City: {0}", city);
                Thread.Sleep(500);
            }
            return citiesArray.Length;
        }
    }

Result


Related Tutorials