在函数上处理互斥

时间:2016-05-09 09:59:30

标签: c# windows mutex

如何锁定函数,以阻止程序的其他实例执行直到它完成?

我认为我需要某种类型的系统互斥锁和WaitOne,但我不确定如何以健壮的方式将它组合在一起。我想的就是......

public static void function()
{
    bool ok;

    using (Mutex mutex = new Mutex(true, "Set-IP Instance", out ok))
    {
        if(!ok)
        {                    
            mutex.WaitOne();
        }

        ...
    }
}  

1 个答案:

答案 0 :(得分:1)

使用此代码(简单版本)可以实现您正在寻找的行为:

using(Mutex mutex = new Mutex(false, "GlobalMutexId"))
{
    mutex.WaitOne();
    //Do your thing
    mutex.ReleaseMutex();
}

或者如果您更喜欢更可重复使用的方法:

public class MutexFactory
{
    private string _name;

    public MutexFactory(string name)
    {
        _name = name;
    }

    public SingleUseMutex Lock()
    {
        return new SingleUseMutex(_name);
    }
}

public class SingleUseMutex : IDisposable
{
    private readonly Mutex _mutex;

    internal SingleUseMutex(string name)
    {
        _mutex = new Mutex(false, name);
        _mutex.WaitOne();
    }

    public void Dispose()
    {
        _mutex.ReleaseMutex();
        _mutex.Dispose();
    }
}

可以像这样使用:

private void TestFunction()
{
    MutexFactory factory = new MutexFactory("YourMutexId");

    for (int i = 0; i < 100; i++)
    {
        // also works for new instances of your program of course
        new Thread(Interlocked).Start(factory);
    }
}

private void Interlocked(object obj)
{
    Guid guid = Guid.NewGuid();
    MutexFactory factory = obj as MutexFactory;
    using (factory.Lock())
    {
        Debug.WriteLine(guid.ToString("N") + " start");
        //Waste Time
        Thread.Sleep(50);
        Debug.WriteLine(guid.ToString("N") + " end");   
    }
}