There are instances where we want to give sole access to a process to a specific thread. We can do this using the lock keyword. This will, therefore, execute this process in a thread-safe manner. Hence, when a thread runs the process it will gain exclusive access to the process for the duration of the lock scope. If another thread tries to gain access to the process inside the locked code, it will be blocked and have to wait its turn until the lock is released.
Locking one thread until the contended resources are available
Getting ready
For this example, we will use tasks. Make sure that you've added the using System.Threading.Tasks; statement to the top of your Demo class.