Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# function inside lock(obj)

Tags:

c#

For the example below, will the lock be release before i++ is executed? In otherwords will the lock be released when a function is called inside a lock?

lock (lockerobject /*which is static*/)
{
   call2anotherFunction();
   i++;
}
like image 895
Ads Avatar asked Dec 04 '22 12:12

Ads


1 Answers

The lock will not be released until the lock block is exited. lock doesn't know or care what code you execute inside the block.

In fact, as a general rule, what happens inside a block is not known to what's outside of it:

if (condition)
{
    // The if doesn't know what happens in here
}

or

using (var reader = XmlReader.Create(url))
{
    // using doesn't care what happens in here
    throw new Exception("Unless...");
} // Dispose will be called on reader here

But the Dispose will only be called because the block is exited, not just because a throw happens inside it.

like image 159
John Saunders Avatar answered Dec 18 '22 05:12

John Saunders