I’m trying to learn threading in C#, and I’ve seen something crop up in few articles but I am not sure I fully understand it: In the given two examples, what would the fundamental difference between getting a lock on ‘this’ vs ‘thisLock’.
Example 1:
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;
}
}
}
Example 2:
class Account
{
decimal balance;
public void Withdraw(decimal amount)
{
lock (this)
{
if (amount > balance)
{
throw new Exception("Insufficient funds");
}
balance -= amount;
}
}
}
From my understanding, I would of thought that ‘thisLock’ only stops other threads from entering that specific area of code.
Were as getting a lock on ‘this’ would stop all operations on the object, i.e. calls to other methods by other threads?
Have I fundamentally miss understood this, or is that the correct conclusion?
Both cases will have the exact same effect. One difference is that other objects cannot see
thisLock, so you can be sure nothing else will reuse the lock. If you lock onthis, another part of code can also lock on the same instance of Account.