// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Threading; public class Lock12 { public static void Test0() { Thread.Sleep(1000); } private static object lck1 = new object(); public static void Test1() { Monitor.Enter(lck1); Thread.Sleep(1000); Monitor.Exit(lck1); } private static object lck2 = new object(); public static void Test2() { lock(lck2) { Thread.Sleep(1000); } } public static void Test(Action a) { DateTime t1 = DateTime.Now; Thread[] t = new Thread[10]; for(int i = 0; i < t.Length; i++) { t[i] = new Thread(new ThreadStart(a)); } for(int i = 0; i < t.Length; i++) { t[i].Start(); } for(int i = 0; i < t.Length; i++) { t[i].Join(); } DateTime t2 = DateTime.Now; Console.WriteLine((t2 - t1).TotalSeconds); } public static void Main(string[] args) { Test(Test0); Test(Test1); Test(Test2); } }