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, 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.
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.
How to do it...
- In the
Demo
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 Demo { private object threadLock = new object(); ...