title: A lock designed for asynchronous applications
body: <p>I have a class which has an inner state which can be changed.</p>
  
  <p>These state changes are never simple, and often consist of several asynchronous operations which occur across multiple threads, such as opening a connection and sending some data</p>
  
  <p>By using a lock and a boolean to indicate whether the state is currently changing I can ensure that only one operation can ever have access to the state at any given time</p>
  
  <pre><code>lock (thisLock) {
  
      while (stateChanging)
          Monitor.Wait(thisLock);
  
  
      stateChanging= true;
  
      //now free to go away and do other things while maintaining exclusive access to the inner state
  
  
  }
  </code></pre>
  
  <p>This works fine, but it means there is needless blocking occurring in threads waiting to get exclusive access the state</p>
  
  <p>So what I envision is a lock based on callbacks, where a state changing operation does something like this -</p>
  
  <pre><code>sharedLock.ObtainLock(delegate() {
  
       //we now have exclusive access to the state
       //do some work
  
       socket = new Socket();
       socket.BeginConnect(hostname, connectcallback);
  
  });
  
  void connectcallback(IAsyncResult result) {
  
      socket.EndConnect(result);
  
      isConnected = true;
  
      sharedLock.ReleaseLock();
  
  
  }
  </code></pre>
  
  <p>Is such a concept common? Does it have a name? Am I approaching things incorrectly?</p>