Disposed Mutex Behavior

  • Thread starter Thread starter Ken Durden
  • Start date Start date
K

Ken Durden

The following code outputs the following:
True
True
Cannot access a disposed object (ObjectDisposedException)

Why does WaitAll differ in behavior from WaitOne?

Mutex mutex = new Mutex();
bool bLocked = mutex.WaitOne();
Console.WriteLine( "bLocked = {0}", bLocked );

IDisposable i = mutex;
i.Dispose();

bLocked = WaitHandle.WaitAll( new WaitHandle[]{ mutex } );
Console.WriteLine( "bLocked = {0}", bLocked );

bLocked = mutex.WaitOne();
Console.WriteLine( "bLocked = {0}", bLocked );


Also, the return value documentation for WaitHandle.WaitAll appears to
be wrong, it changes for each overload in bizarre ways.

Return Value
true when every element in waitHandles has received a signal. If the
current thread receives a request to abort before the signals are
received, this method returns false.

Return Value
true to exit the synchronization domain before the wait; otherwise,
false.

Return Value
true if the method exited the synchronization domain before the wait;
otherwise, false.

Ugh,
-ken
 
Hi Ken,

After running your code the result i got was
True
False
<Exception>

---

Of course you're getting the ObjectDisposed exception because you've
disposed of the mutex at an earlier line, which makes the Mutex handle
become invalid and hence mutex.WaitOne() will definitely fail.

In the case of the WaitAll (which you also invoke after disposing)...
it takes in an array of WaitHandles, and thus if the mutex was disposed
just prior to the WaitAll - the method essentially doesn't get a signal
from any element in the array, hence returns False. (If as you said in
your mail, WaitAll returns True at this point then it would definitely
be very strange!)

Also check out the use of ReleaseMutex / Close instead of Dispose...

Regards,
nalin perera
http://www.geocities.com/nalinperera
 
Back
Top