Search code examples
c#multithreadingmsdnautoresetevent

Does waitany(Array) actually 'set' a event, or does it just return the index of a signaled event


http://msdn.microsoft.com/en-us/library/tdykks7z.aspx

According to the docs the return value is:

"The array index of the object that satisfied the wait."

So that means the index represents a event that has been set and this code would cause a deadlock becuase it would be waiting on itself:

    private static AutoResetEvent waitLock()
    {
        //Wait for any of the events to be signaled 
        AutoResetEvent autoEvent;
        lock(yahooRequests)    //Note: yahoo requests is a array of auto reset events
        {
            int index = AutoResetEvent.WaitAny(yahooRequests);
            autoEvent = yahooRequests[index];
            autoEvent.WaitOne();
        }
        return autoEvent;
    }

And this code would be correct:

private static AutoResetEvent waitLock()
{
    //waitany returns the index of a successfull wait. So this line returns the reference to a autoresetevent.
    return yahooRequests[AutoResetEvent.WaitAny(yahooRequests)];
}

I just want to make sure since (in my humble opinion) the documentation is not 100% clear

EDIT:

My design was flawed I should have been using a semaphore as @Hans Passant pointed out. Since I wanted to ensure N number of yahooRequests had access to a function. But @arno technically answers the initial question. Really wish I could set two accepted asnwers

EDIT:

Also as @Sriram Sakthivel pointed out in the comments the first example would wait on itself forever. But is not actually deadlock.


Solution

  • The WaitHandle.WaitAny method does not set an event. It returns the array index of the object that satisfied the wait. This may need a wait or may also occurr when the event was set before the call to WaitAnywas done. The index will be returned without wait in the latter case.