internal ILoopResult ForEach(IEnumerable <T> source, int maxDegreeOfParallelism) { if (source == null) { throw new ArgumentNullException("source"); } _maxDegreeOfParallelism = OptimizeMaxDegreeOfParallelism(source, maxDegreeOfParallelism); var iterator = source.GetEnumerator(); if (!iterator.MoveNext()) { return(this); } if (_maxDegreeOfParallelism == 1) { Process(iterator); return(this); } // avoid running out of memory. var capacity = Math.Min(512, _maxDegreeOfParallelism); _itemQueue = new LinkedBlockingQueue <KeyValuePair <long, T> >(capacity); _futures = new List <IFuture <Void> >(capacity); try { Submit(StartParallel); } catch (RejectedExecutionException) { Process(iterator); return(this); } bool success; long count = 0; do { success = _itemQueue.TryPut(new KeyValuePair <long, T>(count++, iterator.Current)); }while (success && iterator.MoveNext()); _itemQueue.Break(); WaitForAllTaskToComplete(); return(this); }