There will be a βrightβ way to do this, it will not require you to lock your final shared object and will only require you to perform blocking operations at the end of each local stream loop.
int x = 0; Parallel.For(0, 100, () => 0, //LocalInit (i, loopstate, outerlocal) => { Parallel.For(i + 1, 100, () => 0, //LocalInit (a, loopState, innerLocal) => { return innerLocal + 1; }, (innerLocal) => Interlocked.Add(ref outerlocal, innerLocal)); //Local Final return outerlocal; }, (outerLocal) => Interlocked.Add(ref x, outerLocal)); //Local Final
However, having two nested Parallel statements doing this little work is probably a bad idea. The overhead that you need to consider if you are doing such a little work would be much better to do just one Parallel statement or not at all.
I highly recommend that you download and read Parallel Programming Patterns , which details why small nested parallel loops like this are not a good idea.
Scott Chamberlain
source share