Any way to immediately timeout in WaitOne ()?

In Microsoft.NET, the WaitOne () method

public virtual bool WaitOne(
TimeSpan timeout
)

returns trueif the current instance receives a signal; otherwise false.

My question is, is there a way to get it back false, even if the timeout point has not yet arrived?
Or
In other words, is there a way to immediately call a timeout on WaitOne(), even if the real timeout point has not arrived?

Update:

The project is based on .NET 3.5 , so ManualResetEventSlim may not work (introduced in .NET 4). Thanks @ani anyway.

+4
source share
3 answers

You cannot cancel WaitOne, but you can wrap it:

public bool Wait(WaitHandle yourEvent, WaitHandle cancelEvent, TimeSpan timeOut)
{
   WaitHandle[] handles = new WaitHandle[] { yourEvent, cancelEvent };

   // WaitAny returns the index of the event that got the signal
   var waitResult = WaitHandle.WaitAny(handles, timeOut);  

   if(waitResult == 1)
   {
       return false; // cancel!
   }

   if(waitResult == WaitHandle.WaitTimeout)
   {
       return false; // timeout
   }

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

   // WaitAny returns the index of the event that got the signal
   var waitResult = WaitHandle.WaitAny(handles, timeOut);  

   if(waitResult == 1)
   {
       return false; // cancel!
   }

   if(waitResult == WaitHandle.WaitTimeout)
   {
       return false; // timeout
   }

   return true;
}
+6
source

It seems you want to wait for the signal for a certain time, and you can also cancel the wait operation at runtime.

One way to achieve this is to use ManualResetEventSlimwith a cancellation token using Wait(TimeSpan timeout, CancellationToken cancellationToken). In this case, one of three things will happen:

  • The Wait operation will be completed with true as soon as the event is signaled (before the end of the timeout).
  • The Wait operation will complete with false if the event was not specified at a timeout point.
  • OperationCanceledException , .
+5

If you set an event to signal that it will free the waiting thread;

0
source

Source: https://habr.com/ru/post/1533653/


All Articles