Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Threading.Mutex with Service and Console

my program runs as a service or with console. I have created a System.Threading.Mutex to start only one of the two modes. Here my code

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");
    }
}
}

Starting first the console and then another console the exception is thrown. Starting first the service and the a console doesn't throw the exception. Starting first the console and then the service is the same.

Any ideas? I'm wondering because I think, that it has allready work some months ago, when I implemented the feature.

I'm using .NET 4.0.

Thanks, Freddy

like image 516
Freddy Avatar asked May 08 '26 21:05

Freddy


1 Answers

Probably problem is because your service runs under different credentials, so mutex is not "shared" between users/sessions...
You have to prefix the name of the mutex with "Global\"
Look at this good post.

like image 60
Marco Avatar answered May 11 '26 10:05

Marco