尝试锁定互斥锁或等到解锁

时间:2017-06-24 19:29:10

标签: c# .net

我在一台计算机上运行了一个多实例应用程序。我想在C#中实现以下伪代码:

Mutex mutex = new Mutex(false, "SomeMutex");
while (true)
{
    if (CheckIfCanDoSomething())
    {
        if (mutex.WaitOne(TimeSpan.Zero))
        {
            // I am the first instance that can do the task
            DoSomething();
            mutex.ReleaseMutex();
        }
        else
        {
            // Some other instance was first, wait until it has finished
            mutex.WaitUntilUnlockedWithoutLockingIt();
            DoSomethingElse();
        }
    }
}

基本上,我有一个应用程序的多个实例,即不断检查是否满足某些条件(CheckIfCanDoSomething)来执行某些操作(DoSomething)。问题是,当满足条件时,只有一个应用程序实例应该执行此任务。在CheckIfCanDoSomething任务完成之前,true方法将返回DoSomething

我怎样才能实现mutex.WaitUntilUnlockedWithoutLockingIt()逻辑?

1 个答案:

答案 0 :(得分:1)

嗯,你的伪代码显然有错误。实际上我会创建Mutext方法扩展,它将描述关键部分:

{{1}}

并像这样使用它:

{{1}}
相关问题