Is there a way to do foreach
style iteration over parallel enumerables in C#? For subscriptable lists, I know one could use a regular for
loop iterating an int over the index range, but I really prefer foreach
to for
for a number of reasons.
Bonus points if it works in C# 2.0
.NET 4's BlockingCollection makes this pretty easy. Create a BlockingCollection, return its .GetConsumingEnumerable() in the enumerable method. Then the foreach simply adds to the blocking collection.
E.g.
Hope this helps. BTW I posted a blog about this last night
Andre
Short answer, no.
foreach
works on only one enumerable at a time.However, if you combine your parallel enumerables into a single one, you can
foreach
over the combined. I am not aware of any easy, built in method of doing this, but the following should work (though I have not tested it):Then you can
foreach
over the returned enumerable:If you want to stick to the basics - I rewrote the currently accepted answer in a simpler way:
Zooba's answer is good, but you might also want to look at the answers to "How to iterate over two arrays at once".
Would this work for you?
For C# 2.0, you need to convert the lambda expressions above to delegates.
Note: This utility method uses background threads. You may want to modify it to use foreground threads, and probably you'll want to wait till all threads finish. If you do that, I suggest you create
sources.Length - 1
threads, and use the current executing thread for the last (or first) source.(I wish I could include waiting for threads to finish in my code, but I'm sorry that I don't know how to do that yet. I guess you should use
aWaitHandle
Thread.Join()
.)I wrote an implementation of EachParallel() from the .NET4 Parallel library. It is compatible with .NET 3.5: Parallel ForEach Loop in C# 3.5 Usage:
Implementation: