本文介绍了如何找到C#中的Mutex被获取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 C# 中的 mutex 句柄中找到已获取的 mutex?

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

mutex.WaitOne(timeout) 超时时,它返回 false.但是,我怎样才能从互斥锁句柄中找到它?(也许使用 p/invoke.)

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

更新:

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
}

目前,我正在使用自己的属性 IsAcquired 来确定是否应该释放互斥锁.不是必要的,但更清楚的是,不要使用 IsAcquired 属性表示的信息的辅助副本,而是直接询问互斥锁是否由我获取.由于调用 mutex.ReleaseMutex() 如果不是我获取的就会抛出异常.

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.

(通过 acquired 状态是指当我拥有互斥体时,互斥体处于未发出信号状态.)

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

(我添加了 IsAcquired = false; 感谢 mattdekrey 的帖子.)

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

推荐答案

如你所见,Mutex 类没有公共成员:http://msdn.microsoft.com/en-us/library/system.threading.mutex_members.aspx

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

也没有公开的本地函数:http://msdn.microsoft.com/en-us/library/ms686360%28v=VS.85%29.aspx

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

但是,有一些未记录/不受支持的函数,尤其是在 ntdll.dll 中.这些允许访问系统对象.但是,这些功能可能会在未来的操作系统版本中发生变化或不可用.

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.

这篇关于如何找到C#中的Mutex被获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 11:38
查看更多