.NET Parallel Extensions - For and ForEach methods

01.11.2010 14:34Comments
I decided to make this post to show to those that are not familiar with Parallel Extensions, how easy it is to go parallel with it. Parallel extensions were introduced in .NET 4.0 and it provides two new methods in the class System.Threading.Tasks.Parallel: For and ForEach. These methods allow you to perform tasks in parallel based on a collection of data. Here is a very simple example that clearly illustrates this:
            //collection of data to iterate on
            int[] numbers = new int[]{1, 2, 3, 4, 5};
            var watch = new Stopwatch();

            //Run the tasks sequentially
            foreach( int i in numbers)
            Console.WriteLine("Running sequentially:");
            Console.WriteLine("Elapsed: " + watch.ElapsedMilliseconds.ToString()); //close to 15000


            //Now run them in parallel
            Parallel.ForEach(numbers, i => WaitForSeconds(i));
            Console.WriteLine("Running in parallel:");
            Console.WriteLine("Elapsed: " + watch.ElapsedMilliseconds.ToString()); //close to 5000 (depending on the # of cores)
Notice how easy it is to go from a foreach loop, to a a ForEach method call using a lambda expression. The real secret behind all this is to identify and make sure that the calls that are made to each element in the collection are independent from one another (which is why they can be done in Parallel). If you don't ensure this, you might get random bugs, and different behaviors for the same input (usually something not desireable at all). In adition to For and ForEach methods, parallel extensions also add some extension methods to make IEnumerable into ParallelQuery, and from ParallelQuery to IEnumerable. So if you haven't done so, go ahead and import the System.Threading.Tasks namespace to your project and start playing with it!

comments powered by Disqus