title: How do I make a lock that allows only ONE thread to read from the resource?
body: <p>I have a file that holds an integer ID value. Currently reading the file is protected with <code>ReaderWriterLockSlim</code> as such:</p>
  
  <pre><code>    public int GetId()
      {
          _fileLock.EnterUpgradeableReadLock();
          int id = 0;
          try {
              if(!File.Exists(_filePath))
                  CreateIdentityFile();
  
              FileStream readStream = new FileStream(_filePath, FileMode.Open, FileAccess.Read);
              StreamReader sr = new StreamReader(readStream);
              string line = sr.ReadLine();
              sr.Close();
              readStream.Close();
              id = int.Parse(line);
              return int.Parse(line);
          }
          finally {
              SaveNextId(id);     // increment the id 
              _fileLock.ExitUpgradeableReadLock();
          }
      }
  </code></pre>
  
  <p>The problem is that subsequent actions after <code>GetId()</code> might fail. As you can see the <code>GetId()</code> method increments the ID every single time, disregarding what happens after it has issued an ID. The issued ID might be left hanging (as said, exceptions might occur). As the ID is incremented, some IDs might be left unused.</p>
  
  <p>So I was thinking of moving the <code>SaveNextId(id)</code> out, remove it (the <code>SaveNextId()</code> actually uses the lock too, except that it's <code>EnterWriteLock</code>). And call it manually from outside after all the required methods have executed. That brings out another problem - multiple threads might enter the <code>GetId()</code> method before the <code>SaveNextId()</code> gets executed and they might all receive the same ID.</p>
  
  <p>I don't want any solutions where I have to alter the IDs after the operation, correcting them in any way because that's not nice and might lead to more problems.</p>
  
  <p>I need a solution where I can somehow callback into the FileIdentityManager (that's the class that handles these IDs) and let the manager know that it can perform the saving of the next ID and then release the read lock on the file containing the ID.</p>
  
  <p>Essentialy I want to replicate the relational databases autoincrement behaviour - if anything goes wrong during row insertion, the ID is not used, it is still available for use but it also never happens that the same ID is issued. Hopefully the question is understandable enough for you to provide some solutions..</p>
  
  <p><em>UPDATE: Please see the comments to the answers for more details about the behaviour I want</em></p>