TN. TN. - 1 month ago 15
C# Question

How to find that Mutex in C# is acquired?

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

#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.)

(EDIT: I have added
IsAcquired = false;
thanks to mattdekrey's post.)

Answer

As you may found, there are no public members on Mutex class: http://msdn.microsoft.com/en-us/library/system.threading.mutex_members.aspx

There is also no public native functions for that: http://msdn.microsoft.com/en-us/library/ms686360%28v=VS.85%29.aspx

However, there are some undocumented/unsupported functions especially in ntdll.dll. These allow accessing system objects. However, these functions may change or not be available in future versions of operating system.

So, the answer is: It is not possible using conventional means.