Optimizing independent foreach iterations in .NET3.5

Let's say I have

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

      

Each time through foreach is independent of the others. Is there a quick way to instruct the CLR to each execute a separate thread, or speed it up by initially parallelizing it?

Perhaps he already knows how to do it.

I know I could spawn threads and run them, but that would be swelling if there was an attribute or flag I could set that would take care of this for me.

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

something like

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

      

+2


source to share


1 answer


You can try Parallel.For from the Parallel Task Library. This can work really well if you get the granularity right. For more details, see the following article:

Optimize managed code for multi-core machines
http://msdn.microsoft.com/en-us/magazine/cc163340.aspx



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

+12


source







All Articles