// 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.Collections.Generic; using System.Threading.Tasks; namespace SerializedAccess { public class TemperatureLogger { private List measurements; private int max; public TemperatureLogger(int measurement) { measurements = new List(); measurements.Add(measurement); max = measurement; } public int GetMax() { lock(this) { return max; } } public void Update(int measurement) { lock(this) { measurements.Add(measurement); if(measurement > max) { max = measurement; } } } } public class Program { private const int REP = 1000; private const int N = 100; public static void Main(string[] args) { DateTime dt1 = DateTime.Now; for(int j = 0; j < REP; j++) { try { TemperatureLogger tl = new TemperatureLogger(0); int[] v = new int[N]; for(int i = 0; i < N; i++) { v[i] = N/2 - Math.Abs(N/2 - i); } Task[] t = new Task[N]; for(int i = 0; i < N; i++) { int tempv = v[i]; t[i] = Task.Factory.StartNew(() => tl.Update(tempv)); } Task.WaitAll(t); int res = tl.GetMax(); if(res != N/2) Console.WriteLine("Ooops - wrong result: {0}", res); } catch(Exception ex) { Console.WriteLine("Ooops - exception: {0} {1}", ex.Message, ex.InnerException.Message); } } DateTime dt2 = DateTime.Now; Console.WriteLine("Time: {0} s", (dt2 - dt1).TotalSeconds); } } }