带有服务和控制台的System.Threading.Mutex

Fre*_*ddy 2 c# service mutex windows-services console-application

我的程序作为服务或控制台运行.我创建了一个System.Threading.Mutex,只启动两种模式中的一种.在这里我的代码

public class MyServer 
{
// Private variable
System.Threading.Mutex serverMutex;

public MyServer ()
{
    bool createdNew;
    ServerMutex = new System.Threading.Mutex(true, "MyServerMutex", out createdNew);
    if (!createdNew)
    {
        throw new Exception("Another server instance is running");
    }
}
}
Run Code Online (Sandbox Code Playgroud)

首先启动控制台,然后启动另一个控制台,抛出异常.首先启动服务,控制台不会抛出异常.首先启动控制台,然后服务是相同的.

有任何想法吗?我想知道,因为我认为,几个月前,当我实现该功能时,它已经全部工作了.

我正在使用.NET 4.0.

谢谢,弗雷迪

Mar*_*rco 7

可能问题是因为您的服务在不同的凭据下运行,因此互斥体不会在用户/会话之间"共享"...
您必须在互联网的名称前加上"Global\"
看看这个好帖子.