The Task Parallel Library which is now part of the Reactive Extensions for .NET Framework makes stuff like this trivial. There's a set of Parallel
constructs for parallelizing your code, and a set of thread-safe Concurrent{Container}s
which you can use with them.
Here's an example of squaring a bunch of numbers, using a 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);
}
}
}
The ConcurrentBag
is a regular IEnumerable
, as you can see I'm using a regular, non-parallel foreach
to print out the results at the end.
Note: All this stuff is actually standard in .NET 4.0, you just need Rx if you want it for .NET 3.5.