C# - Parallel Computing
Wednesday, April 15th, 2009Concurrent programming in C# - Parallel.Do method
This is a simple example of concurrent programming in C#. I will discuss about Do method. This example use Parallel Extensions to the .NET published in December 2007, so this is not up to date article. This extension provides System.Threading namespace and Class Parallel. We will use here it’s method Do.
public static void Do( params Action[] actions )
This method “executes each of the provided actions inside a discrete, asynchronous task”. It doesn’t
finishes until each of provided actions has completed. That means, it will finish when the slowest action finishes. For example let’s imagine
that we have 2 long running methods called method1() and method2(). If you call them in sequential manner we’ll need to
wait until method1() finishes its job, then w’ll wait method2() finishes its job. But if we run them in parallel we’ll only need to wait as much as the longest of this two methods is executing. Let’s see an example.
public class ParalellDemo
{
private static double x = 1000000000;
private static void method1()
{
for (double i = 0; i < x; i++) ;
}
private static void method2()
{
for (double i = 0; i < x; i++) ;
}
static void Main(string[] args)
{
Stopwatch watch = new Stopwatch();
watch.Start();
// *** sequential
method1();
method2();
watch.Stop();
Console.WriteLine("Not parallel: " +
(watch.ElapsedMilliseconds / 1000.0).ToString() +
"s");
watch.Reset();
watch.Start();
// *** parallel
Parallel.Do(() => method1(), () => method2());
watch.Stop();
Console.WriteLine("Parallel: " +
(watch.ElapsedMilliseconds / 1000.0).ToString() +
"s");
}
}
After starting this little demo, the time which you get running the above program, depends about your computer CPU. On my computer (Core 2 Duo, 2.49GHz, 3GB Ram) I get this result:
That’s all for now. For you who want some more, please read about an excellent extension for .NET - ParallelFX.
More links:

Recent Comments