Locking is essential in parallel programs. It restricts code from being executed by more than one thread at the same time. Exclusive locking is used to ensure that only one thread can enter a particular section of code at a time.
The simplest way to use synchronization in c# is with the lock
keyword. The lock
keyword works by marking a block of code as a critical section by obtaining a mutual exclusion lock for an object running a statement and then releasing the lock.
In this recipe, we are going to create a class that represents a bank account. An object of this class will be shared by a couple of parallel tasks that will be making a series of withdrawals for random amounts. The critical section of code in the Withdraw
method that updates the balance of the shared account object will be protected by a lock
statement.