Parallel Programming with .NET Parallel Extensions

Download this episode


This video demonstrates the use of Parallel Extensions to the .NET Framework.   Parallel Extensions requires .NET 3.5 and the final version will be part of the .NET 4.0 Framework when released.  These extensions introduce new classes and functionality into the System.Threading namespace.  It's now considerably easier to parallelize a code block without creating explicit threads.

Windows Server 2008 R2 and Windows 7 introduce new system-level features (e.g. User-Mode-Scheduling) that both the C++ Concurrency Runtime and the .NET Parallel Extensions extend.   Developers may easily target current and legacy platforms using the new runtime and extensions. 

First, a project is shown that counts the number of primes up to a given upper bound.  Each number is checked by seeing if it’s divisible by any number between 2 and its square root.  Each prime number found increases the count.  The main control is a standard for loop.

Next, the same code is converted to work with the new Parallel.For() method.  This takes the lower and upper bound, and a delegate for the action to take.  Using a Lamda expression, the original loop body is made to work using i => {} syntax.  When this code is run, it is clear that a bug has surfaced in the form of a bad prime count.  This is actually a common multithreading bug, stemming from the use of the increment operator, ++.  Using the Interlocked.Increment() method fixes the problem.

The next demo starts with a LINQ query and converts to a Parallel LINQ, or PLINQ, query.  After demonstrating the original loop which uses Enumerable.Range() to generate a range of numbers, it is shown that ParallelEnumerable.Range() creates an enumerator that is automatically multi-threaded.

Finally, to demonstrate a more general-usage solution, any IEnumerable collection can easily be parallelized using the expression method AsParallel().  Thus, a collection students of type List<Student> could be used in a LINQ as a parallel query by simply using it as students.AsParallel().

Learn more about Parallel Computing on Windows at the MSDN Concurrency Dev Center.



Available formats for this video:

Actual format may change based on video formats available and browser capability.

    The Discussion

    • User profile image
      Modi Gendelman

      Wonderfull presentation, very helpful, covers the basics of parallel extension with detailed examples.

    Comments closed

    Comments have been closed since this content was published more than 30 days ago, but if you'd like to send us feedback you can Contact Us.