private readonly object syncRoot = new object(); void Main(string[] args) { Foo(); doThings(); Bar(); } void Foo() { Monitor.Enter(syncRoot); } void Bar() { Monitor.Exit(syncRoot); }
[ Edit ]
When you use lock
, this is what happens under the hood in .NET 4:
bool lockTaken = false; try { Monitor.Enter(syncRoot, ref lockTaken); // code inside of lock } finally { if (lockTaken) Monitor.Exit(_myObject); }
Alex aza
source share