0

I need to write a piece of code that is:

  1. Run on every configured interval
  2. Stops after a certain amount of time OR after a condition is met.

I found that I can use a Task with CancellationToken but I can't see any option to run a it again and again within an interval.

Another option I saw is to use System.Threading.Timer - but then I can't cancel the process if a condition is met.

Can someone suggest an elegant solution ?

ohadinho
  • 6,894
  • 16
  • 71
  • 124
  • You can check the condition after the timer is triggered (first action) and skip the processing if needed. – Jeroen Heier Jan 01 '18 at 12:50
  • Looking for the Timer.Enabled property? Or a while-statement in a Task with a Task.Delay() inside the loop? The task is easier to stop reliably. – Hans Passant Jan 01 '18 at 13:22

1 Answers1

-1

You can do this easily using Reactive Extensions:

int maxDurationInseconds = 5;
bool condition = true;

var timer = Observable.Interval(TimeSpan.FromSeconds(1))
    .TakeWhile(i => i <= maxDurationInseconds)
    .TakeWhile(i => condition)
    .Subscribe(i => 
    {
        Console.WriteLine(i);
    });

Console.ReadLine();     

timer.Dispose();

The above code will show the elapsed seconds until the threshold is reached or the condition becomes false. i represent the amount of seconds passed.

A good reference for Rx can be found here. Or take a look at the GitHub repo.

Peter Bons
  • 26,826
  • 4
  • 50
  • 74