Wednesday, December 18, 2013

C# Multithreading Loop with Parallel.For or Parallel.ForEach

Loop is such a trivial and so frequently used thing. And sometimes loops just killing performance of the whole application. I want the loop perform faster, but what can I do?

Starting from .NET Framework 4 we can run loops in parallel mode using Parallel.For method instead of regular for or Parallel.ForEach instead of regular foreach. And the most beautiful thing is that .NET Framework automatically manages the threads that service the loop!

But don't expect to receive performance boost each time you replace your for loop with Parallel.For, especially if your loop is relatively simple and short. And keep in mind that results will not come in proper order because of parallelism.

Now let's see the code. Here is our regular loop:
for (int i = 1; i < 1000; i++)
{
    var result = HeavyFoo(i);
    Console.WriteLine("Line {0}, Result : {1} ", i, result);
}
And here is how we write it with Parallel.For:
Parallel.For(1, 1000, (i) =>
{
    var result = HeavyFoo(i);
    Console.WriteLine("Line {0}, Result : {1} ", i, result);
});
Same story with Parallel.ForEach:
foreach(string s in stringList)
{
    var result = HeavyFoo(s);
    Console.WriteLine("Initial string: {0}, Result : {1} ", s, result);
}

Parallel.ForEach(stringList, s =>
{
    var result = HeavyFoo(s);
    Console.WriteLine("Initial string {0}, Result : {1} ", s, result);
});
Use with caution! :)

No comments:

Post a Comment