如何防止此异常:值不在预期范围内。使用WaitHandle.WaitAny方法?

时间:2016-07-26 09:31:19

标签: c# wpf multithreading waithandle

  

QueueCompareProcessThread()的异常消息:值不会下降   在预期范围内。追踪:at   System.Threading.WaitHandle.WaitMultiple(WaitHandle [] waitHandles,   Int32 millisecondsTimeout,Boolean exitContext,Boolean WaitAll)at   System.Threading.WaitHandle.WaitAny(WaitHandle [] waitHandles,Int32   millisecondsTimeout,布尔exitContext)at   System.Threading.WaitHandle.WaitAny(WaitHandle [] waitHandles)

当我在线程中的WaitAny上使用WaitHandle方法时,我得到了上述异常。请帮我解决这个问题。这是我的代码部分:

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);
    }
}

任何人都可以对WaitAny方法有所了解并帮我解决问题吗?

1 个答案:

答案 0 :(得分:0)

您需要确保pHandles数组实际包含元素,并且每个元素仅包含一次。 documentation表示如果ArgumentException是没有元素的数组,并且.NET Framework版本为2.0或更高版本”,则会引发waitHandles

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