Mutexes are OS-level handles. They'll get closed when your process does (if you don't close them sooner, that is.)
edit
Ok, I clearly misunderstood the example and the question. If you're just trying to detect whether another instance exists, you'd create a named mutex (or similar object) and simply check for its existence without ever locking on it.
The call to WaitOne
locks on it, taking ownership, while ReleaseMutex
gets rid of it (so long as there are no additional calls to WaitOne
). If you end the thread without releasing the mutex fully, it does leave the object in a bad state, as explained in the text Micah quotes.
I took your question as being about whether you close the handle before the process completes, which is another thing entirely.
additional
At the SDK [API][1] level, you can call CreateMutex
with the expectation of failing when a mutex of the same name has already been created. In .NET (well, in 4.0, at least), there's a [constructor][2] that fills a createdNew
bool.
[1]: http://msdn.microsoft.com/en-us/library/ms682411(VS.85).aspx CreateMutex
[2]: http://msdn.microsoft.com/en-us/library/bwe34f1k(v=VS.90).aspx Mutex