I would like to - for obscure reasons thou shall not question - start a lock in a method, and end it in another. Somehow like:
object mutex = new object();
void Main(string[] args)
{
lock (mutex)
{
doThings();
}
}
Would have the same behaviour 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 a block syntax, of course. I'm aware that locks are not meant to be used like this, but I'm more than open to the creative and hacky solutions of S/O. :)
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 happening 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With