I’ve got a simple .NET program, which checks to see if another instance has been started:
Mutex mutex = new Mutex(false,"MyMutexName");
if (!mutex.WaitOne(1))
return;
try{
//do stuff
}
catch{ //exceptions}
finally
{
mutex.ReleaseMutex();
}
My question is, what exactly happens to the mutex if you forget to release it when the program ends? Is it visible in some windows control panel component? Where does it live?
It is a named mutex so it is visible and can be opened in other processes. Windows uses a simple reference count on the handle. If you don’t Dispose() it explicitly yourself then the finalizer will close the handle for you. If your program bombs hard and never executes the finalizer then Windows will do it when it cleans up the resources used by your program.
That will automatically decrement the reference count. If that counts down to zero (no other processes have a handle open on it) then the kernel object is released.
In other words: you don’t have a problem no matter how badly things turn out. The actual mutant object lives in the kernel memory pool. You can see it with the SysInternals’ WinObj tool.