You cannot cancel WaitOne, but you can wrap it:
public bool Wait(WaitHandle yourEvent, WaitHandle cancelEvent, TimeSpan timeOut)
{
WaitHandle[] handles = new WaitHandle[] { yourEvent, cancelEvent };
var waitResult = WaitHandle.WaitAny(handles, timeOut);
if(waitResult == 1)
{
return false;
}
if(waitResult == WaitHandle.WaitTimeout)
{
return false;
}
return true;
}
Just pass in the handle you want to wait and the handle to cancel the wait and timeout.
Extra
As an extension method, so it can be called similarly to WaitOne:
public static bool Wait(this WaitHandle yourEvent, WaitHandle cancelEvent, TimeSpan timeOut)
{
WaitHandle[] handles = new WaitHandle[] { yourEvent, cancelEvent };
var waitResult = WaitHandle.WaitAny(handles, timeOut);
if(waitResult == 1)
{
return false;
}
if(waitResult == WaitHandle.WaitTimeout)
{
return false;
}
return true;
}
source
share