Sammy Ageil

Lead by example

Execute multiple Tasks in .Net 4.0

June 14
by Sammy Ageil 14. June 2011 16:17

Yesterday I exaplained one of many ways to execute multiple threads and be notified when all threads have executed.
See http://www.sammyageil.com/post/2011/06/13/How-to-detect-multiple-threads-completion-in-Net.aspx
Today we will see similar using System.Threading.Tasks namespace.

lets get to the code.

 

public static Random random = new Random();
        static void Main(string[] args)
 {
List<Task> tasks = new List<Task>
            {
                Task.Factory.StartNew(()=>FirstJob("A")),
                Task.Factory.StartNew(()=>SecondJob("B")),
                Task.Factory.StartNew(()=>ThirdJob("C"))
            };
            Task.WaitAll(tasks.ToArray());
            Console.WriteLine("--------------ALL JOBS COMPLETED---------------");
            Console.Read();
       }

 

here is the code to simulate long running tasks

 

public static void FirstJob(string s)
        {
            Console.WriteLine("First Job started at {1}, With param recieved as {0}", s, DateTime.Now);
            System.Threading.Thread.Sleep(random.Next(5000, 20000));
            Console.WriteLine("First Job Completed at {1}, With param recieved as {0}", s, DateTime.Now);
        }
        public static void SecondJob(string s)
        {
            Console.WriteLine("Second Job started at {1}, With param recieved as {0}", s, DateTime.Now);
            System.Threading.Thread.Sleep(random.Next(5000, 20000));
            Console.WriteLine("Second Job Completed at {1}, With param recieved as {0}", s, DateTime.Now);
        }
        public static void ThirdJob(string s)
        {
            Console.WriteLine("Third Job started at {1}, With param recieved as {0}", s, DateTime.Now);
            System.Threading.Thread.Sleep(random.Next(5000, 20000));
            Console.WriteLine("Third Job Completed at {1}, With param recieved as {0}", s, DateTime.Now);
        }

 

Hint: if you are not familiar with Tasks namespace, comment Task.WaitAll(tasks.ToArray()); and run the console app again.
  Console.WriteLine("--------------ALL JOBS COMPLETED---------------"); will be the first line to execute.

Tags: , ,

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading