E
E
estry2020-12-11 10:12:47
C++ / C#
estry, 2020-12-11 10:12:47

How to stop execution when the time is reached?

Hello.
There is a loop in which certain code is executed, for example:

while(true)
{
  
  method1();
  
  method2();
  
  method3();
  
}


How to stop this loop after 3 minutes?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vasily Bannikov, 2020-12-11
@vabka

Use CancellationToken and CancellationTokenSource with the CancelAfter
method But it would be better if you could describe the task more specifically, otherwise it looks like an XY problem .

F
freeExec, 2020-12-11
@freeExec

https://docs.microsoft.com/en-us/dotnet/api/system...
https://metanit.com/sharp/tutorial/12.5.php

E
eRKa, 2020-12-11
@kttotto

Because You didn't say you're using TPL or writing in WinForms or WPF, so I'm assuming it's just plain synchronous code somewhere in the console.
Start a timer above your loop, check the time inside the loop and, upon reaching it, exit the loop through break. On the knee, without checks, but I think you will catch the meaning

var dateTimeStart = DateTime.Now;
const PERIOD = 3 * 60 * 1000;
while(true)
{
    ...
    var dateTimeNow = DateTime.Now;
    var interval = dateTimeNow - dateTimeStart;
    if(interval.Milliseconds > PERIOD)
    {
        break;
    }
}

C
cicatrix, 2020-12-11
@cicatrix

If the code is synchronous without multithreading, then

var t = DateTime.Now;
var interval = new TimeSpan(0,3,0);
while(DateTime.Now - t < interval)
{
 \\ ...
}

If asynchronous or methods are long, then by timer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question