Reputation: 10507
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
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
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
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
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
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
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