Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine ManualResetEvent and token.WaitHandle.WaitOne

I got:

internal void Start(CancellationToken token)
{
   while (!token.IsCancellationRequested)
   {
       //do work
       token.WaitHandle.WaitOne(TimeSpan.FromSeconds(67));
   }       
}

So i start this method in new Task and do some work in loop untill i need to cancel it with token Some times i need to force new loop iteration, without waiting this 67 seconds. I think i need something like:

public ManualResetEvent ForceLoopIteration { get; set; }

Meanwhile i cant understand how to use it with token. Maybe something like WaitHandle.WaitAny()?

like image 248
nuclear sweet Avatar asked May 14 '14 10:05

nuclear sweet


People also ask

What is WaitOne in C#?

WaitOne(TimeSpan, Boolean) Blocks the current thread until the current instance receives a signal, using a TimeSpan to specify the time interval and specifying whether to exit the synchronization domain before the wait. public: virtual bool WaitOne(TimeSpan timeout, bool exitContext); C# Copy.

What is AutoResetEvent and how it is different from ManualResetEvent?

An AutoResetEvent resets when the code passes through event. WaitOne() , but a ManualResetEvent does not.

How to use WaitHandle in c#?

static WaitHandle[] waitHandles = new WaitHandle[] { new AutoResetEvent(false), new AutoResetEvent(false) }; // Define a random number generator for testing. static Random r = new Random(); static void Main() { // Queue up two tasks on two different threads; // wait until all tasks are completed.


1 Answers

Youre on the right way, try this:

WaitHandle.WaitAny(
    new[] { token.WaitHandle, ForceLoopIteration },
    TimeSpan.FromSeconds(67));

This waits for the occurence of one of the following

  • cancelation is requested on token
  • ForceLoopIteration is set
  • timeout of 67 seconds has been elapsed
like image 147
abto Avatar answered Sep 20 '22 12:09

abto