Starting and ending locks in various ways

I would like - for unclear reasons you will not doubt - start the lock in the method and end it in another. Something like:

object mutex = new object(); void Main(string[] args) { lock (mutex) { doThings(); } } 

Will have the same behavior as:

 object mutex = new object(); void Main(string[] args) { Foo(); doThings(); Bar(); } void Foo() { startLock(mutex); } void Bar() { endlock(mutex); } 

The problem is that the lock keyword works in block syntax, of course. I know that locks are not meant to be used in this way, but I'm more than open to creative and hacked S / O solutions. :)

+7
source share
1 answer
 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); } 
+16
source

All Articles