Disposed Mutex Behavior

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
 
N

Nalin Perera

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

ThreadPool and WaitHandle 1
AbandonedMutexException 1
CF 2.0 multithread app accessing database 12
Is Mutex Owned? 13
Problem with mutex 1
Problem with named mutex 3
About Thread Completion Notify. 2
Timer.Dispose 0

Top