Consider this example:
var x = 0;
for (var i = 0; i < 100; i++ )
{
for (var a = i+1; a < 100; a++)
x += 1;
}
When printing x we always get 4950. What about if I want to parallelise this?
This is what I come up with
Parallel.For(0, 100, i => Parallel.For(i + 1, 100, a => { x += 1; }));
However this does Not print 4950 each time I run it. Why?
Parallel Extensions helps you with task creation, allocation, running and rendezvous, in a near-imperative syntax. What it doesn’t do is take care of every kind of thread safety (one of the pitfalls). You are trying to make parallel threads simultaneously update a single shared variable. To do anything like this correctly, you have to introduce e.g. locking.
I’m not sure what you’re trying to do. I assume your code is just a placeholder or experiment. Parallelization is only suitable when you can isolate your different pieces of work; not when you constantly have to rendezvous with shared data.