To complement, lock
is a kind of semaphore. In fact through it it is possible to deploy a data structure capable of controlling the processing traffic that is called #
The lock
turns on a red light telling any code that tries to access that stretch of memory that it is prohibited to do until the light goes out. Note that although it looks like a traffic light, it is not. This is why lock
itself can be used on a semaphore which is a slightly more sophisticated structure.
It indicates to the entire application that at that time something will be done with the object that can not be interrupted. That no part of the application can consider the state of the object until it is released because the operation at that time may be inconsistent or incomplete.
When your code is compiled the statement lock
becomes a code equivalent to this:
bool lockWasTaken = false;
var temp = thisLock;
try {
Monitor.Enter(temp, ref lockWasTaken);
if (amount > balance) {
throw new Exception("Insufficient funds");
}
balance -= amount;
} finally {
if (lockWasTaken) {
Monitor.Exit(temp);
}
}
I placed GitHub for future reference .
Note that you can achieve the same result using only the library but it is not recommended.
In codes that you are sure will never have threads you do not need and should not use this type of timing. For some operations the performance cost of running the methods of the class Monitor
may be prohibitive.
See the Reference Source to understand the inner workings of the class (not that help a lot).