How do I collect return values from Parallel.ForEach?

You’ve discarded it in here. ParallelLoopResult result = Parallel.ForEach(words, word => AddB(word)); You probably want something like, ParallelLoopResult result = Parallel.ForEach(words, word => { string result = AddB(word); // do something with result }); If you want some sort of collection at the end of this, consider using one of the collections under System.Collections.Concurrent, like … Read more

Break parallel.foreach?

Use the ParallelLoopState.Break method: Parallel.ForEach(list, (i, state) => { state.Break(); }); Or in your case: Parallel.ForEach<ColorIndexHolder>(ColorIndex.AsEnumerable(), new Action<ColorIndexHolder, ParallelLoopState>((ColorIndexHolder Element, ParallelLoopState state) => { if (Element.StartIndex <= I && Element.StartIndex + Element.Length >= I) { Found = true; state.Break(); } }));

Parallel.ForEach() vs. foreach(IEnumerable.AsParallel())

They do something quite different. The first one takes the anonymous delegate, and runs multiple threads on this code in parallel for all the different items. The second one not very useful in this scenario. In a nutshell it is intended to do a query on multiple threads, and combine the result, and give it … Read more

Parallel foreach with asynchronous lambda

If you just want simple parallelism, you can do this: var bag = new ConcurrentBag<object>(); var tasks = myCollection.Select(async item => { // some pre stuff var response = await GetData(item); bag.Add(response); // some post stuff }); await Task.WhenAll(tasks); var count = bag.Count; If you need something more complex, check out Stephen Toub’s ForEachAsync post.