using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace CriticalSectionExample { class Program { public static int x; public static int y; static void SwapXY() { int z = x; x = y; #region Some potentially time consuming operation for (int i = 0; i < int.MaxValue /40 ; i++) ; #endregion y = z; } static void Main(string[] args) { for (int i = 1; i < 10000; i++) { x = 1; y = 0; Thread one = new Thread(SwapXY); Thread two = new Thread(SwapXY); one.Start(); two.Start(); one.Join(); two.Join(); if (x != 1 || y != 0) { Console.WriteLine("Incorrect swap on try {0}", i); } } } } }