Using the Parallel class
This recipe shows how to use the Parallel
class APIs. We will learn how to invoke methods in parallel, how to perform parallel loops, and tweak parallelization mechanics.
Getting ready
To work through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe can be found in BookSamples\Chapter7\Recipe1
.
How to do it...
To invoke methods in parallel, perform parallel loops, and tweak parallelization mechanics by using the Parallel
class, perform the given 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.Linq; using System.Threading; using System.Threading.Tasks;
Add the following code snippet below the
Main
method:static string EmulateProcessing(string taskName) { Thread.Sleep(TimeSpan.FromMilliseconds(new Random(DateTime.Now.Millisecond).Next(250, 350))); Console.WriteLine("{0} task was processed on...