How to do it...

  1. In the Demo 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 Demo 
{
private object threadLock = new object();
public void LockThreadExample()
{

}

private void ContendedResource(int sleepSeconds)
{

}
}
It is considered to be a best practice to define the object to lock on as private.
  1. Add three tasks to the 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");
  1. In the 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}");
  1. Back in the console application, add the following code to instantiate a new Demo class and call the LockThreadExample() method:
        Demo oRecipe = new Demo(); 
oRecipe.LockThreadExample();
Console.ReadLine();
  1. Run the console application and look at the information output to the console window:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.150.123