poy
poy

Reputation: 10507

c# lock return/continue/break

If I have the following code:

lock(SyncRoot){ return value; }

Will the SyncRoot be unlocked before the return statement?

I tried walking through the code in VS2005, but it doesn't actually show one way or another. It looks like it DOES unlock it, but I want to make sure.

Upvotes: 3

Views: 3256

Answers (7)

user3778410
user3778410

Reputation: 51

If you have something like ` int i = 0; object o = new object();

        while (i < 100)
        {
            lock (o)
            {
                if (i == 10)
                    continue;
            }

            ++i;
        }`

this will result in a deadlock because it will wait forever to acquire the lock saved from the previous execution context before continue

Upvotes: 2

Botz3000
Botz3000

Reputation: 39600

Yes, you can think of it expanding to something like this:

Monitor.Enter(obj);
try {
    var result = value;
}
finally {
    Monitor.Exit(obj);
}
return result;

If you look at the generated IL, it is something like that. If value were an expression though, it would be evaluated before releasing the lock. The return is executed after releasing the lock.

The finally block is called in any case, so yes, the lock is released.

Upvotes: 4

Tudor
Tudor

Reputation: 62439

Remember that lock actually uses Monitor.Enter/Monitor.Exit in the background. The expanded version of your code is in fact this

Monitor.Enter (SyncRoot);
try
{
    return value;
}
finally { Monitor.Exit (SyncRoot); }

The finally block is guaranteed to be executed before the method actually returns, so the lock is released.

Upvotes: 2

Toan Nguyen
Toan Nguyen

Reputation: 11581

No, the lock is released only after the return statement.

Upvotes: 0

Roy Dictus
Roy Dictus

Reputation: 33139

It will unlock after the block is executed.

This syntax is similar to using, btw. The only reason the lock is outside of the block is to show that there is a lock at start, unlock at end functionality.

Upvotes: 2

Joachim Isaksson
Joachim Isaksson

Reputation: 180897

Yes, it calculates value (if value were an expression this may be important), then unlocks and returns. A lock() is always unlocked automatically when you exit its scope, no matter how you do it.

Upvotes: 2

M4N
M4N

Reputation: 96551

Yes it does unlock no matter how you exit the block (i.e. return, break, throw, etc).

See MSDN - lock statement for more details:

The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section.
...
The lock keyword calls Enter at the start of the block and Exit at the end of the block.

Upvotes: 3

Related Questions