AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Friday, 27 April 2018

How to create parallel task in C#?

In this article I will explain How to handle one or more task at a time. Please read below scenarios to understand.
Before starting create a method "DoSomeWork" that will hold execution for few second. Its just for understanding.

private void DoSomeWork(int val)
     //Wait here .

1- Run one at a time
// Wait on a single task to complete
Task taskA = Task.Factory.StartNew(() => DoSomeWork(20000));
Console.WriteLine("taskA has completed.");

2- Wait for all task to complete

Task taskA = Task.Factory.StartNew(() => DoSomeWork(2000));
Task taskB = Task.Factory.StartNew(() => DoSomeWork(3000));
Task taskC = Task.Factory.StartNew(() => DoSomeWork(1000));
Task.WaitAll(taskA, taskB, taskC);
Console.WriteLine("taskA, TaskB and taskC has completed.");

3- Wait till any one of the task to complete

private double RandomStuff()
   int i = rand.Next(1000000);           
   return DateTime.Now.Millisecond;

First created a method "RandomStuff" which will take different execution time every time.

Task<double>[] tasks = new Task<double>[3];

//Created Three different tasks.
tasks[0] = Task<double>.Factory.StartNew(() => RandomStuff());
tasks[1] = Task<double>.Factory.StartNew(() => RandomStuff());
tasks[2] = Task<double>.Factory.StartNew(() => RandomStuff());

int index = Task.WaitAny(tasks);
double d = tasks2[index].Result;
Console.WriteLine("task[{0}] completed first with result of {1}.", index, d);

Above example where three different task will execute & first completed task will be considered in the output.


Post a Comment

  • Popular Posts
  • Comments