Parallel namespace in .NET 4.0

Published On: Feb 11, 2010

It was only a couple of months ago that I purchased a new laptop. A very shiny Dell Studio 15, with a core i7 in it.  I have been very happy with it. But it wasn't long before I started to notice a problem, when I would run programs it would max  out one maybe two of the cores and the rest of the computer would be idle.  For a machine that has 8 logical cores (4 Physical w/HT) that's a whole lot of waste without a whole lot of return.  Then I started to think about the problems that come up with doing multi threading in code.  It's flat hard, and in many cases if  its not something that you were thinking about from the very begining you are in for a world of hurt.  So you could imagine how happy I was when I heard about the Parallel namespace that is included in version 4.0 of the .net framework. The idea was that because multithreading is difficult especially when you are talking about systems that are generally designed by people whom have little deep understanding about the technology that they are dealing with, it was refreching to see that the people in redmond were thinking about us.  Now it is as simple as working with a single namespace and making sure that your resources are properly taken care of. How well does it work?  I decided to put together a little test to test the whole thing out. So I decided to create a small code segment that would simulate a thousand segments processing at 10ms a piece and the results were almost exactly what I expected, I tested this on my new laptop, so it's splitting the work between 8 logical processors. Single Console Run Time : 9990ms Parallel Console Run Time : 1216ms While this is not a super scientific task since we can see that the work that is being done is just putting the thread to sleep, it does effectively show that the framework for parallel core processing is working and can be implemented with little extra work. Here's the code so you can test and see what you come up with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
static void Main(string[] args)
{
int MaxCount = 1000;
 
System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
 
timer.Start();
for (int i = 1; i < MaxCount; i++)
{
Syscode(i);
}
timer.Stop();
Console.WriteLine("Single Console Run Time : {0}ms", timer.ElapsedMilliseconds);
timer.Reset();
 
timer.Start();
Action sysDelegate = new Action(Syscode);
Parallel.For(1, MaxCount, sysDelegate);
timer.Stop();
 
Console.WriteLine("Parallel Console Run Time : {0}ms", timer.ElapsedMilliseconds);
Console.Read();
}
 
public static void Syscode(int x)
{
System.Threading.Thread.Sleep(10);
}

Comments