Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start and finish lock in different methods

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. :)

like image 863
Lazlo Avatar asked May 30 '11 20:05

Lazlo


1 Answers

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);
}    
like image 157
Alex Aza Avatar answered Sep 20 '22 23:09

Alex Aza