A leader is one who knows the way, goes the way and shows the way

Execute multiple Tasks in .Net 4.0

In my previous article I explained one of many ways to execute multiple threads and be notified when all threads have executed using C#.
Today we use Framework 4.0 TPL System.Threading.Tasks namespace to perform the same task.

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.This occurs because Task.WaitAll is a blocking call.

Pingbacks and trackbacks (1)+

Comments are closed