sexta-feira, 7 de outubro de 2011

Simple Parallel ForEach in C#.NET 2.0

A simple Parallel ForEach implementation for Microsoft C#.NET 2.0:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ParallelTest
{
    public class Parallel
    {
        public delegate void Process();

        public static void ForEach<T>(IEnumerable<T> enumerable, Action<T> action) 
        {
            IEnumerator<T> enumerator = enumerable.GetEnumerator();

            int threadCount = Environment.ProcessorCount;

            Process process = delegate()
            {
                while (true)
                {
                    T item = default(T);

                    lock (enumerator)
                    {
                        if (enumerator.MoveNext())
                            item = enumerator.Current;
                        else
                            return;
                    }

                    action(item);
                }
            };

            IAsyncResult[] asyncResults = new IAsyncResult[threadCount];

            for (int i = 0; i < threadCount; ++i)
                asyncResults[i] = process.BeginInvoke(null, null);

            for (int i = 0; i < threadCount; ++i)
                process.EndInvoke(asyncResults[i]);
        }
    }
}

Nenhum comentário:

Postar um comentário

Feel free to comment on the immoderately.