How to prevent this Exception: Value does not fall within the expected range. with WaitHandle.WaitAny method?

456 Views Asked by At

Exception at QueueCompareProcessThread() Message:Value does not fall within the expected range. Trace: at System.Threading.WaitHandle.WaitMultiple(WaitHandle[] waitHandles, Int32 millisecondsTimeout, Boolean exitContext, Boolean WaitAll) at System.Threading.WaitHandle.WaitAny(WaitHandle[] waitHandles, Int32 millisecondsTimeout, Boolean exitContext) at System.Threading.WaitHandle.WaitAny(WaitHandle[] waitHandles)

I get the exception above when I use the WaitAny method on a WaitHandle in a thread. Please help me to sort out the issue. Here is my part of the code:

public void QueueCompareProcessThread(QueueProcesses Qp)
{
    try
    {
        WaitHandle[] pHandles = Qp.GetRunningProcessesHandles();
        WaitHandle.WaitAny(pHandles);
        Qp.RemoveExitedProcess();   // clearing the process list 
        // strange behavior is while clearing the process list i'm getting the exception in the thread Waitany method
        // Does Waitany method still working after it returns?
    }
    catch (Exception e)
    {
        utils.Log("QProc Exception at QueueCompareProcessThread() Message:" + e.Message + " Trace:" + e.StackTrace);
    }
}

Can anyone please give some idea about the WaitAny method and help me to sort out the issue?

1

There are 1 best solutions below

0
Dirk Vollmar On

You need to make sure that the pHandles array actually contains elements and that each element is only contained once. The documentation states that an ArgumentException is thrown if waitHandles is an array with no elements, and the .NET Framework version is 2.0 or later”.

if (pHandles.Any())
{
    WaitHandle.WaitAny(pHandles);
}