Lock and Monitor
Learn to synchronize access to shared resources using the lock statement and the System.Threading.Monitor class to prevent race conditions.
We'll cover the following...
In the previous lesson, we saw how 10 threads acting on a shared bank balance caused data loss due to race conditions. To fix this, we need to ensure that only one thread can perform the deposit operation at a time.
The basic principles behind different thread synchronization mechanisms are almost the same. Whenever a thread needs to use a shared resource, it locks it. If two threads attempt to use the same shared resource, one of them must wait while the other finishes its work.
The lock keyword
The most straightforward way to achieve synchronization is to enclose the critical section of our code within a lock block. We must use a dedicated object to serve as the lock token: