text
stringlengths
0
13.4k
Chapter 41: Parallel processing using .Net
framework
This Topic is about Multi core programming using Task Parallel Library with .NET framework. The task parallel
library allows you to write code which is human readable and adjusts itself with the number of Cores available. So
you can be sure that your software would auto-upgrade itself with the upgrading environment.
Section 41.1: Parallel Extensions
Parallel extensions have been introduced along with the Task Parallel Library to achieve data Parallelism. Data
parallelism refers to scenarios in which the same operation is performed concurrently (that is, in parallel) on
elements in a source collection or array. The .NET provides new constructs to achieve data parallelism by using
Parallel.For and Parallel.Foreach constructs.
//Sequential version
foreach (var item in sourcecollection){
Process(item);
}
// Parallel equivalent
Parallel.foreach(sourcecollection, item => Process(item));
The above mentioned Parallel.ForEach construct utilizes the multiple cores and thus enhances the performance in
the same fashion.
GoalKicker.com – .NET Framework Notes for Professionals
129
Chapter 42: Task Parallel Library (TPL)
Section 42.1: Basic producer-consumer loop
(BlockingCollection)
var collection = new BlockingCollection<int>(5);
var random = new Random();
var producerTask = Task.Run(() => {
for(int item=1; item<=10; item++)
{
collection.Add(item);
Console.WriteLine("Produced: " + item);
Thread.Sleep(random.Next(10,1000));
}
collection.CompleteAdding();
Console.WriteLine("Producer completed!");
});
It is worth noting that if you do not call collection.CompleteAdding();, you are able to keep adding to the
collection even if your consumer task is running. Just call collection.CompleteAdding(); when you are sure there
are no more additions. This functionality can be used to make a Multiple Producer to a Single Consumer pattern
where you have multiple sources feeding items into the BlockingCollection and a single consumer pulling items out
and doing something with them. If your BlockingCollection is empty before you call complete adding, the
Enumerable from collection.GetConsumingEnumerable() will block until a new item is added to the collection or
BlockingCollection.CompleteAdding(); is called and the queue is empty.
var consumerTask = Task.Run(() => {
foreach(var item in collection.GetConsumingEnumerable())
{
Console.WriteLine("Consumed: " + item);
Thread.Sleep(random.Next(10,1000));
}
Console.WriteLine("Consumer completed!");
});
Task.WaitAll(producerTask, consumerTask);
Console.WriteLine("Everything completed!");
Section 42.2: Parallel.Invoke
var actions = Enumerable.Range(1, 10).Select(n => new Action(() =>
{
Console.WriteLine("I'm task " + n);
if((n & 1) == 0)
throw new Exception("Exception from task " + n);
})).ToArray();
try
{
Parallel.Invoke(actions);
}
catch(AggregateException ex)