// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace E { public class Program { public static void Main(string[] args) { int[] a = Enumerable.Range(1, 1000).ToArray(); DateTime t1, t2; int sum; sum = 0; t1 = DateTime.Now; foreach(int a1 in a) { Thread.Sleep(10); // simulate lots of work sum += a1; } t2 = DateTime.Now; Console.WriteLine("single thread : result = {0} time = {1}", sum, (t2 - t1).TotalSeconds); sum = 0; t1 = DateTime.Now; Parallel.ForEach(a, (a1) => { Thread.Sleep(10); // simulate lots of work sum += a1; }); t2 = DateTime.Now; Console.WriteLine("multi thread : result = {0} time = {1}", sum, (t2 - t1).TotalSeconds); sum = 0; t1 = DateTime.Now; object mylock = new object(); Parallel.ForEach(a, (a1) => { Thread.Sleep(10); // simulate lots of work lock(mylock) { sum += a1; } }); t2 = DateTime.Now; Console.WriteLine("multi thread synched : result = {0} time = {1}", sum, (t2 - t1).TotalSeconds); } } }