Good afternoon, there is a cycle:

while('условие') { // код } 

A new iteration of the loop is required to occur one second after it starts.

  Thread.Sleep(1000); 

does not fit, because he will fall asleep for a second already after the end of the cycle, and the time will be 1000 + the cycle time

  • one
    and if the cycle does not have time to execute in one second? - Grundy
  • What is not satisfied with the usual timer? - Grundy
  • We assume that it will have time. - Anton Popov
  • 2
    the usual timer plus the variable flag that the task is being executed and if the task did not have time, then respond otherwise just start the task. - vitidev
  • Try to look at the system time at the beginning of the cycle and consult it periodically in the body of the cycle. If the difference reaches 1 second - goto to the beginning of the cycle. - Anatol

3 answers 3

For example, you can:

 while (условие) { var oneSecond = Task.Delay(TimeSpan.FromSeconds(1)); // ожидание начинается тут в фоне // тело цикла await oneSecond; // а здесь мы заканчиваем начатое ожидание } 
  • And if the loop body will be executed for more than 1 second? - Anatol
  • @Anatol: There's nothing to be done, await will work instantly, but the total execution time will be how long the iteration was done. - VladD
  • Use Stopwatch and subtract the time spent on the method from the second - Serginio
  • @Serginio: And how is your suggestion better than the method of the answer? Technically, it is clearly more difficult and less readable (try it yourself), and what benefits does it bring? - VladD
  • one

I’ll add another solution based on Asynchronously wait for Task to complete with timeout

 while(true) { var task = SomeOperationAsync(); // Выполняем тело цикла var oneSecond = Task.Delay(TimeSpan.FromSeconds(1)); // ожидание начинается тут в фоне if (await Task.WhenAny(task, oneSecond ) == task) { // задача выпонилась раньше 1 секунды await oneSecond; // а здесь мы заканчиваем начатое ожидание } else { // прошла секунда, а задача ещё не выпонилась // делаем телодвижения и дожидаемся окончания задачи await task; // или можно запустить новую без ожидания старой } } 

    Use Stopwatch

    And you can run new threads ....