I have the following code:
using (Mutex mut = new Mutex(false, MUTEX_NAME)) { if (mut.WaitOne(new TimeSpan(0, 0, 30))) {
I set a breakpoint in the if block and ran the same code in another instance of Visual Studio. As expected, .WaitOne call .WaitOne . However, to my surprise, as soon as I continue in the first instance and the using block completes, I get an exception in the second process about the abandoned Mutex.
The fix is ββto call ReleaseMutex :
using (Mutex mut = new Mutex(false, MUTEX_NAME)) { if (mut.WaitOne(new TimeSpan(0, 0, 30))) {
Now everything works as expected.
My question is: Usually the IDisposable point clears any state into which you insert things. Perhaps I have several expectations and releases in the using block, but when the Mutex handle is located, should it not be automatically released? In other words, why do I need to call ReleaseMutex if I'm in a using block?
I am also concerned that if the code inside the if block crashes, I will remain mutexes lying around.
Is there any use for placing Mutex in a using block? Or, should I just update the Mutex instance, wrap it in try / catch and call ReleaseMutex() in the finally block (basically implement what I thought Dispose() )
Mike Christensen Aug 21 '14 at 17:40 2014-08-21 17:40
source share