Frage

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.

War es hilfreich?

Lösung

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.

Andere Tipps

So that means the index represents a event that has been waited on

No, all events in the array were waited on. The returned index is simply the first one that was Set(). It will be reset after WaitAny() returns. So the first snippet indeed makes no sense, you don't want to call WaitOne() again. The second snippet doesn't make much sense, there isn't anything distinctive about the AutoResetEvent object you return. In particular it isn't signaled anymore since an ARE automatically resets itself. You really do need to know the index to know which particular job got done.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top