Question:
I was looking at an MSDN article, but it wasn't quite clear why I should use 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;
}
}
}
Answer:
Lock
is a very useful tool when you need to grant exclusive access to a given resource, or ensure Thread safety .
This function makes use of an object as a synchronization flag (in your example, the thislock
object).
In the example code, the first thread to execute the Withdraw
method will get the lock
from the thislock
object, and will execute the code block. Any other thread that tries to execute the same method instance will go into WaitState (or wait state ) if it encounters the lock
instruction and another thread has the access right.
A queue is created, and the waiting threads will receive a FIFO-style lock release ( First In, First Out ).