问题
I am trying named system mutex approach to synchronize two processes-
- a c# windows service
- a desktop c# app
When the mutex is created, process that didn't create the mutex doesn't seem to detect the existing mutex. Below in more detail:
Windows service is responsible for creating the mutex(No prefixes-Global/Local etc. Just a normal named system mutex) as follows:
Mutex myMutex= null;
try
{
myMutex= Mutex.OpenExisting(myMutexName);
}
catch (WaitHandleCannotBeOpenedException x)
{
//doesn't exist.
try
{
this.GetLogger().Info("Create Mutex");
bool createdNew = false;
new Mutex(false, myMutexName, out createdNew);
if (!createdNew) throw new Exception("Unable to create Mutex");
}
catch (Exception ex)
{
this.Stop();
}
}
catch (Exception x)
{
this.Stop();
}
finally
{
if (myMutex!= null)
{
try
{
myMutex.ReleaseMutex();
}
catch(Exception x)
{
this.GetLogger().Warn("Unable to release mutex");
}
}
}
I have this in onStart(). Also, elsewhere in the service I synchronize on this mutex.
Now, in the application I use it thus:
Mutex myMutex= null;
try
{
myMutex= Mutex.OpenExisting(this.myMutexName);
myMutex.WaitOne();
//do required stuff
}
catch (WaitHandleCannotBeOpenedException wcbox)
{
//doesn't exist yet. service not running??
this.GetLogger().Error("Background Service is not Running");
shutdownApp();
}
finally
{
if (myMutex!= null)
{
try
{
myMutex.ReleaseMutex();
}
catch (Exception x)
{
}
}
}
My issues:
With service is running, the app throws WaitHandleCannotBeOpenedException which means it doesn't see the mutex which exists (I verified this using the tool "WinObj", mutex exists under "BaseNamedObjects" as type "Mutant"). Why? I run the service under same account as I am logged in. Even without, that shouldn't be the issue because named mutex is operating system wide object right?
I am not exactly clear on when the mutex will get destroyed. Currently, I see that the mutex gets created when I start the service and when I stop the service, I see the mutex no longer exists(WinObj). Does that mean mutex is garbage collected when there is no one waiting on it and when the creator process ends?
In general, what is the life cycle of a named system mutex. Specifically, when does it die?
回答1:
Since you want to share a mutex across sessions you must use either the Global
namespace, or create your own private namespace.
As it stands, you are not specifying a namespace. And whilst the service defaults to use the global namespace, your interactive application will be using the local namespace.
回答2:
@david i use a tool called google to easily find it, and we are running in production with interactive services detection enabled with an interactive service. interactive services detection cannot be started unless you switch that registry key. i don't know what the debate is here: it's there, its documented, and google can easily point you to it.
来源:https://stackoverflow.com/questions/14488481/named-system-mutex-not-recognized