How to find that Mutex in C# is acquired?

Posted by TN on Stack Overflow See other posts from Stack Overflow or by TN
Published on 2010-06-10T09:35:00Z Indexed on 2010/06/11 2:12 UTC
Read the original article Hit count: 348

Filed under:
|
|
|
|

How can I find from mutex handle in C# that a mutex is acquired?

When mutex.WaitOne(timeout) timeouts, it returns false. However, how can I find that from the mutex handle? (Maybe using p/invoke.)

UPDATE:

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();
    }

    #endregion
}

Currently, I am using my own property IsAcquired 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 IsAcquired property, but rather to ask directly the mutex whether it is acquired by me. Since calling mutex.ReleaseMutex() throws an exception if it is not acquired by me.

(By acquired state I mean that the mutex is in not-signaled state when I am owning the mutex.)

© Stack Overflow or respective owner

Related posts about c#

Related posts about synchronization