Example #1
0
        /// <summary>
        /// Parallel ForEach method.
        /// </summary>
        /// <remarks>Source: http://www.codeproject.com/KB/dotnet/PoorMansParallelForEach.aspx</remarks>
        public static void ForEach <T>(IEnumerable <T> enumerable, Action <T> action)
        {
            int threadCount = Environment.ProcessorCount;

            object syncRoot = new object();

            if (enumerable == null)
            {
                return;
            }

            IEnumerator <T> enumerator = enumerable.GetEnumerator();

            InvokeAsync <T> del = InvokeAction;

            T[] seedItemArray = new T[threadCount];
            List <IAsyncResult> resultList = new List <IAsyncResult>(threadCount);

            for (int i = 0; i < threadCount; i++)
            {
                bool moveNext;

                lock (syncRoot)
                {
                    moveNext         = enumerator.MoveNext();
                    seedItemArray[i] = enumerator.Current;
                }

                if (moveNext)
                {
                    IAsyncResult iAsyncResult = del.BeginInvoke
                                                    (enumerator, action, seedItemArray[i], syncRoot, i, null, null);
                    resultList.Add(iAsyncResult);
                }
            }

            foreach (IAsyncResult iAsyncResult in resultList)
            {
                del.EndInvoke(iAsyncResult);
                iAsyncResult.AsyncWaitHandle.Close();
            }
        }
Example #2
0
        public static void ForEach <T>(IEnumerable <T> enumerable, System.Action <T> action)
        {
            var syncRoot = new object();

            if (enumerable == null)
            {
                return;
            }

            var enumerator = enumerable.GetEnumerator();

            InvokeAsync <T> del = InvokeAction;

            var seedItemArray = new T[NumberOfParallelTasks];
            var resultList    = new List <System.IAsyncResult>(NumberOfParallelTasks);

            for (int i = 0; i < NumberOfParallelTasks; i++)
            {
                bool moveNext;

                lock (syncRoot)
                {
                    moveNext         = enumerator.MoveNext();
                    seedItemArray[i] = enumerator.Current;
                }

                if (moveNext)
                {
                    var iAsyncResult = del.BeginInvoke
                                           (enumerator, action, seedItemArray[i], syncRoot, i, null, null);
                    resultList.Add(iAsyncResult);
                }
            }

            for (int i = 0, resultListCount = resultList.Count; i < resultListCount; i++)
            {
                var iAsyncResult = resultList[i];
                del.EndInvoke(iAsyncResult);
                iAsyncResult.AsyncWaitHandle.Close();
            }
        }