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…
In the
Recipes
class, add an object calledthreadLock
with theprivate
modifier. Then, add two methods calledLockThreadExample()
andContendedResource()
that take an integer of seconds to sleep as a parameter:public class Recipes { private object threadLock = new object(); public void LockThreadExample...