public static void ListExample() { var list = new List <int>(); for (int i = 0; i < 1000; i++) { list.Add(i); } int count = 0; object countLck = new object(); // Object to box counter BoxedInt countObj = new BoxedInt { Counter = 0 }; Parallel.ForEach(list, (item) => { Console.WriteLine($"I am working on item {item}"); // Atomically increment count.... Interlocked.Increment(ref count); // .. or do it with locks, to isolate a critical section lock (countLck) // An object is required here. { count++; } // Typically, you lock the entire object, if possible // we previously used 'count', which is _not_ an object lock (countObj) { countObj.Counter++; } }); Console.WriteLine($"count now is {count}"); Console.WriteLine($"countObj.Count now is {countObj.Counter}"); }
public static void ArrayExample() { const int size = 4; int [] A = new int[size]; for (int i = 0; i < size; i++) { A[i] = i; } for (int i = 0; i < size; i++) { Console.WriteLine($"A[{i}] is {A[i]}"); } Parallel.ForEach(A, (item) => { item *= 2; Console.WriteLine($"item now is {item}"); }); for (int i = 0; i < size; i++) { Console.WriteLine($"A[{i}] is {A[i]}"); } var boxedList = BoxedInt.CreateList(A); Parallel.ForEach(boxedList, (item) => { item.Counter *= 2; }); foreach (var i in boxedList) { Console.WriteLine(i); } }