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.
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.
Recipes
class, add an object called threadLock
with the private
modifier. Then, add two methods called LockThreadExample()
and ContendedResource()
that take an integer of seconds to sleep as a parameter:public class Recipes { private object threadLock = new object(); public void LockThreadExample() { } private void ContendedResource(int sleepSeconds) { } }
LockThreadExample()
method. They will create threads that try to access the same section of code simultaneously. This code will wait until all the threads have completed before terminating the application:Task thread1 = Task.Factory.StartNew(() => ContendedResource(3)); Task thread2 = Task.Factory.StartNew(() => ContendedResource(5)); Task thread3 = Task.Factory.StartNew(() => ContendedResource(2)); Task.WaitAll(thread1, thread2, thread3); WriteLine("All tasks completed");
ContendedResource()
method, create a lock using the private
threadLock
object and then make the thread sleep for the amount of seconds passed to the method as a parameter:int threadID = Thread.CurrentThread.ManagedThreadId; lock (threadLock) { WriteLine($"Locked for thread {threadID}"); Thread.Sleep(sleepSeconds * 1000); } WriteLine($"Lock released for thread {threadID}");
Recipes
class and call the LockThreadExample()
method:Chapter7.Recipes oRecipe = new Chapter7.Recipes(); oRecipe.LockThreadExample(); Console.ReadLine();
We can see that thread 11
gained exclusive access to the contended resource. At the same time, thread 11
and thread 12
tried to access the contended resource locked by thread 11
. This then caused the other two threads to wait until thread 11
had completed and released the lock. The result of this is that the code is executed in an orderly manner, as can be seen in the console window output. Each thread waits its turn until it can access the resource and lock its thread.
3.144.19.243