Sammy Ageil

Disambiguation of Technologies

Execute multiple Tasks in .Net 4.0

Yesterday I explained one of many ways to execute multiple threads and be notified when all threads have executed.
See here.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.

Pingbacks and trackbacks (1)+

Comments are closed