I have multiple objects (say circles) inside a square grid. Each circle is surrounded by grid vertices (say 4). Two circles can have the same surrounding grid vertices. Each circle updates its surrounding grid vertices.
I try locking the vertices, but I get an incorrect result when I run the code in parallel. Any ideas where the code could be flawed?
Any other approach I could use to execute the code correctly in parallel?
Parallel.ForEach(ArrayOfCircles, circle =>
{
for (var i = 0; i < circle.SurroundingVertices.Count; i++)
{
var n = circle.SurroundingVertices.ElementAt(i);
lock (n)
{
n.ContactNormal[0] += circle.Volume;
n.ContactNormal[1] += circle.Volume;
}
}
});