using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace InterlockedExample { class Program { public static object syncObject; public static int x; public static int y; static void SwapXY() { lock (syncObject) { int z = x; x = y; #region Some potentially time consuming operation for (int i = 0; i < int.MaxValue / 20; i++) ; #endregion y = z; } } static void Main(string[] args) { syncObject = new object(); for (int i = 1; i < 1000; 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); } else { Console.WriteLine(i); } } } } }