title: Lock object based on a condition in c#
body: <p>I need to lock a piece of code based on the value of a variable or a property. Assume my method is being called and pass UserData object.</p>
  
  <pre><code>UserData contains two properties 
  
  UserID and Marks
  </code></pre>
  
  <p>And the lock code currently is like</p>
  
  <pre><code>var l=new Object();
  lock(l)
  {
  //Update marks of a particualr user id to UserData.Marks
  }
  </code></pre>
  
  <p>Now it'll lock everything that comes for this method, Say it is updating marks of UserID=1, it'll still lock the future calls of other User IDs, I want it to lock requests for that particular user id which is accessing the lock, in this Case User 1. Other should move freely.</p>
  
  <p>What I was thinking that rather create an new object for locking, create a custom class for lock which contains the property of User ID. When the request comes I create a lock based on that particular value. I don't even know if this is possible. Kindly guide me in correct direction.</p>