title: Conditional locking based on value
body: <p>I am writing a web service that allows users to create jobs within the system. Each user has an allowance of the number of jobs they can create. I have a method which checks that the user has some remaining credits which looks like this:</p>
  
  <pre><code>private bool CheckRemainingCreditsForUser(string userId)
  {
      lock(lockObj)
      {
         var user = GetUserFromDB(userId);
         if (user.RemaingCredit == 0) return false;
         RemoveOneCreditFromUser(user);
         SaveUserToDB(user);
      }
  }
  </code></pre>
  
  <p>The problem I can see with this approach is that if multiple different users make a request at the same time they will only get processed one at a time which could cause performance issues to the client. Would it be possible to do something like this?</p>
  
  <pre><code>private bool CheckRemainingCreditsForUser(string userId)
  {
      //If there is a current lock on the value of userId then wait 
      //If not get a lock on the value of userId
      var user = GetUserFromDB(userId);
      if (user.RemaingCredit == 0) return false;
      RemoveOneCreditFromUser(user);
      SaveUserToDB(user);
      //Release lock on the value of userId
  }
  </code></pre>
  
  <p>This would mean that requests with different userIds could be processed at the same time, but requests with the same userId would have to wait for the previous request to finish</p>