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(() => ...

Get C# 7 and .NET Core 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.