0

要求:

A. 1 用户登录可以System.Windows.FormProcessName.
B. 2 个不同的用户登录每个都能够System.Windows.FormProcessName.
C. MutexChecker在它自己的类中而不是 的成员,Form因为处理互斥锁的责任会根据用户操作从一种形式更改为另一种形式。
D. SaidForm在 Mutex 创建后异步启动。所以我无法执行using声明。

问题:

在其他 SO 帖子中,我看到类似于以下标记为“不安全”的代码。但是,没有给出代码被标记为“不安全”的原因。相反,提供了一个全局互斥锁作为解决方案。全局互斥锁在机器范围内工作,因此不符合要求。

我试过的:

mutexChecker.RunCheck()来自说的电话System.Windows.Form

public class MutexChecker:IDisposable
{
    private Mutex mutex;

    public bool RunCheck()
    {
        bool createdNew;
        mutex = new Mutex(initiallyOwned: true, name: "AppName", createdNew: out createdNew);

        if (!createdNew)
        {
            MessageBox.Show("AppName is already running.  Please complete the other note before opening a new window.");
        }

        return createdNew;
    }

    public void Dispose()
    {
        mutex.ReleaseMutex();//ERROR: safe handle has been disposed
        mutex.Dispose();//Does not always release the mutex for some unknown reason
    }

Form.Dispose.

问题

如何安全地创建满足要求的互斥锁?

4

1 回答 1

0

为了以异步方式处理处理我的处置的多种形式Mutex,我提出了一个event指定处置时间。否则,我只是在构建后立即转储不必要的互斥锁:

public class MutexChecker
{
    private Mutex mutex;
    private const string instanceName = "AppName";
    private bool createdNew = false;

    public bool RunCheck()
    {            
        mutex = new Mutex(initiallyOwned: true, name: instanceName, createdNew: out createdNew);

        if (createdNew)
        {
            HelperClass.shutdown += Dispose;
        }
        else
        {
            MessageBox.Show("AppName is already running.  Please complete the other note before opening a new window.");
            mutex.Dispose();//dump...I don't need this instance
        }

        return createdNew;
    }

    void Dispose()
    {
        HelperClass.shutdown -= Dispose;
        mutex.Dispose();        
    }
}
于 2013-02-06T19:32:16.740 回答