This recipe shows how to handle many asynchronous tasks running simultaneously. We will learn how to be notified effectively when all tasks are complete or any of the running tasks have to finish their work.
To start this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter4\Recipe8
.
For running tasks in parallel, perform the following steps:
Start Visual Studio 2012. Create a new C# Console Application project.
In the
Program.cs
file, add the followingusing
directives:using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks;
Add the following code snippet below the
Main
method:static int TaskMethod(string name, int seconds){ Console.WriteLine("Task {0} is running on a thread id{1}. Is thread pool thread: {2}", name,Thread.CurrentThread.ManagedThreadId,Thread.CurrentThread.IsThreadPoolThread); Thread.Sleep...