Knowledge Management Banner

Knowledge Management Banner

C# : Monitor , Lock : Part 30

Lock
  • It ensures that only a single thread can access a shared resource.
  • If same resource is accessed by multiple thread than it may affect the output, hence using lock it makes sure that only one thread can access the resource.
  • In example below Increase is a shared resource which is declared as public, if there are multiple using the same resource than it may change the output every time thread access the same resource.

   public class DemoClass  
   {  
     public int Increase;  
     static object _lock = new object();  
     public void IncrementNumber()  
     {  
       lock (_lock)  
       {  
         Increase++;  
       }  
     }  
   }  

Monitor
  • The function of monitor is same as that of lock
  • Monitor.enter will lock the resource and monitor.exit will release the resource as shown in example below
  • If you need more advance control for locking like condition, etc than you can use Monitor
   public class DemoClass  
   {  
     public int Increase;  
     static object _lock = new object();  
     bool LockInit = false;  
     public void IncrementNumber()  
     {  
       Monitor.Enter(_lock, ref LockInit);  
       try  
       {  
         Increase++;  
       }  
       catch (Exception e)  
       {  
       }  
       finally  
       {  
         if (LockInit)  
           Monitor.Exit(_lock);  
       }  
     }  
   }  


No comments

Powered by Blogger.