Freddy
Freddy

Reputation: 693

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

Upvotes: 2

Views: 1854

Answers (2)

Julien Roncaglia
Julien Roncaglia

Reputation: 17837

As Marco said your mutex should be named with something like :

string.Format(@"Global\{0}", mutexName);

to appear in the global namespace (visible to all logged in users). If you need to manipulate the mutex once created by the service you will also need to specify who could manipulate it :

var users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);

var security = new MutexSecurity();
security.AddAccessRule(new MutexAccessRule(users, MutexRights.Synchronize, AccessControlType.Allow));
security.AddAccessRule(new MutexAccessRule(users, MutexRights.Modify, AccessControlType.Allow));

new Mutex(false, name, out createdNew, security);

Upvotes: 3

Marco
Marco

Reputation: 57593

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.

Upvotes: 7

Related Questions