Locking one thread until the contended resources are available

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 execute this process in a thread-safe manner. Therefore, 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.

Getting ready

For this example, we will use tasks. Make sure that you have added the using System.Threading.Tasks; statement to the top of your Recipes class.

How to do it…

  1. In the Recipes class, add an object called threadLock with the ...

Get C# Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.