C#: Parallel.For with Interlocked

Parallel.For runs the iterations of a loop on several threads. The body must be safe to run concurrently: iterations may not depend on each other, and shared variables must be protected. Adding to one shared total from every iteration is a data race if done with a plain +=.

C#
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

class Program {
  static void Main() {
    long total = 0;
    Parallel.For(1, 1001, i => {
      Interlocked.Add(ref total, (long)i * i);
    });
    Console.WriteLine("Parallel.For: " + total);

    long viaLinq = Enumerable.Range(1, 1000).AsParallel().Sum(i => (long)i * i);
    Console.WriteLine("PLINQ:        " + viaLinq);
  }
}
Read the full lesson