The parallel task library, which is now part of the Reactive Extensions for.NET Framework , makes such things trivial. There are a set of Parallel constructors for parallelizing code and a set of thread-safe Concurrent{Container}s that you can use with them.
Here's an example of plotting the number of rows using Parallel.For and a ConcurrentBag to store the results.
using System.Threading.Tasks; using System.Collections.Concurrent; namespace ParallelTest { class Program { static void Main(string[] args) { var results = new ConcurrentBag<int>(); Parallel.For(0, 10, i => { results.Add(i * i); }); foreach (int i in results) System.Console.WriteLine(i); } } }
ConcurrentBag is a regular IEnumerable , as you can see that I am using a regular, non-parallel foreach to print the results at the end.
Note. All this is actually standard in .NET 4.0, you just need Rx if you want it for .NET 3.5.
source share