0

We all familiar with the lock in C#,

and we all know that we have to lock with an Object in order to distinguish between diffrent unrelated critical sections on the code like this:

class Account  
{  
    decimal balance;  
    private Object thisLock = new Object();  

    public void Withdraw(decimal amount)  
    {  
        lock (thisLock)  
        {  
            if (amount > balance)  
            {  
                throw new Exception("Insufficient funds");  
            }  
            balance -= amount;  
        }  
    }  
}

but does anyone knows how the C# class lock uses this unique object in order to lock and distinguish between locks? i've searched every where and tried to look my self at the type lock, but i couldn't find nothing.

does anyone knows the answer?

yonBav
  • 1,695
  • 2
  • 17
  • 31
  • 1
    According to referencesource all the `Monitor` methods (`lock` is syntax sugar for `Monitor.Enter`) end up being `InternalCalls` so I can't tell you for certain. https://referencesource.microsoft.com/#mscorlib/system/threading/monitor.cs,0f82d5416be09a59,references However, based on the MSDN description in the remarks where it discusses value types/boxing, it's obvious that the object's reference/memory location is somehow taken into account. https://msdn.microsoft.com/en-us/library/de0542zz(v=vs.110).aspx#Remarks – pinkfloydx33 Oct 01 '17 at 09:58
  • 3
    "lock class" does not help thinking about this correctly, `lock` is a keyword in C# language. The compiler implements it by using the Monitor class. Its TryEnter() method requires an object, only to keep track of the lock state. Most of the Monitor class is implement inside the CLR and written in C++, the implementation details are [pretty gritty](https://stackoverflow.com/a/14923685/17034). – Hans Passant Oct 01 '17 at 10:01

0 Answers0