views:

88

answers:

1

Let's say I have

foreach(int x in xs[]) // xs is an array of int
{
x++;
}

Each time through the foreach is independent of the others. Is there a quick way to instruct the CLR to do each on a seperate thread or speed it up by natively parallelising it?

Maybe it already knows to do this.

I know you I could create threads and start them but it would be swell if there was an attribute or flag I could set that would take care of it for me.

My actual code is more complex but each iteration through the foreach is also free of effect between iterations.

something like

[parallelize maxThreads=5]
foreach(int x in xs[]) // xs is an array of int
{
x++;
}
+11  A: 

You could try a Parallel.For from the Task Parallel Library. This could work really well if you get the granularity right. See the following article for more details:

Optimize Managed Code For Multi-Core Machines
http://msdn.microsoft.com/en-us/magazine/cc163340.aspx

The Task Parallel Library for .NET 3.5 SP1 can be downloaded from this page. Here is a direct link.

Robert Harvey
This is awesome! Thanks for the tip
Matt
Didn't know about that, thanks.
Ed Swangren