My Technical Notes

Wednesday, 6 August 2014

C# - Running two Tasks in Parallel

When programming, sometimes there are two bits of code which can be executed in parallel because they do not rely on each other.

To do this, we can use the Task class in the System.Threading.Tasks namespace. Below is a bit of code which illustrates the concept:


var taskOne = Task.Run(() => { Thread.Sleep(500); return 1; });
var taskTwo = Task.Run(() => { Thread.Sleep(1000); return 2; });

Task.WaitAll(taskOne, taskTwo);

Console.WriteLine("task one result: " + taskOne.Result + "\r\ntask two result: " + taskTwo.Result);

If the above code were to be executed sequentially, then it would take 1.5 seconds in total (1000ms + 500ms). However because the two tasks are run in parallel, it takes as long as its longest process, which takes 1 second.

No comments: