Tuesday, May 31, 2016

Parallelism in C#

Types of Parallelism in C#


C# supports two main models of parallelism:
  1. Data parallelism: where an operation is applied to each element in a collection.
  2. Task parallelism: where independent computations are executed in parallel.
A sequential for loop in C#:
int n = ...
for (int i = 0; i<=n; i++)
{
// ...
});

A parallel for loop in C#:
int n = ...
Parallel.For(0, n, i =>
{
// ...
});

  • The language construct for is translated into a(higher-order) function Parallel.For.
  • The argument to Parallel.For is an anonymous method, specifying the code to be performed in each loop iteration.
  • The arguments to this anonymous method are the start value, the end value and the iteration variable.


We can limit the degree of parallelism like this:
var options = new ParallelOptions() {
MaxDegreeOfParallelism = 2 };
Parallel.For(0, n, options, i =>
{
fibs[i] = Fib(i);
});


Parallel loops have two ways to break or stop a loop
instead of just one.
  1. Parallel break, loopState.Break(), allows all steps with indices lower than the break index to run before terminating the loop.
  2. Parallel stop, loopState.Stop(), terminates the loop without allowing any new steps to begin. 



No comments:

Post a Comment

Encrypt/Decrypt the App.Config

Program.cs using System; using System.Diagnostics; using System.IO; namespace EncryptAppConfig {     internal class Program     {         pr...