title: How to find that Mutex in C# is acquired?
body: <p>How can I find from mutex handle in C# that a mutex is acquired?</p>
  
  <p>When <code>mutex.WaitOne(timeout)</code> timeouts, it returns <code>false</code>. However, how can I find that from the mutex handle? (Maybe using p/invoke.)</p>
  
  <p><strong>UPDATE</strong>:</p>
  
  <pre><code>public class InterProcessLock : IDisposable
  {
      readonly Mutex mutex;
  
      public bool IsAcquired { get; private set; }
  
      public InterProcessLock(string name, TimeSpan timeout)
      {
          bool created;
          var security = new MutexSecurity();
          security.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow));
          mutex = new Mutex(false, name, out created, security);
          IsAcquired = mutex.WaitOne(timeout);
      }
  
      #region IDisposable Members
  
      public void Dispose()
      {
          if (IsAcquired)
          {
              mutex.ReleaseMutex();
              IsAcquired = false;
          }
      }
  
      #endregion
  }
  </code></pre>
  
  <p>Currently, I am using my own property <code>IsAcquired</code> to determine whether I should release a mutex. Not essential but clearer, would be not to use a secondary copy of the information represented by <code>IsAcquired</code> property, but rather to ask directly the mutex whether it is acquired by me. Since calling <code>mutex.ReleaseMutex()</code> throws an exception if it is not acquired by me.</p>
  
  <p>(By <em>acquired</em> state I mean that the mutex is in <em>not-signaled</em> state when I am <em>owning</em> the mutex.)</p>
  
  <p>(EDIT: I have added <code>IsAcquired = false;</code> thanks to <a href="https://stackoverflow.com/questions/3013212/how-to-find-that-mutex-in-c-is-acquired/3019775#3019775">mattdekrey's post</a>.) </p>