简体   繁体   中英

Stop running the code after 15 seconds

I'm trying to write something to stop running the code after 15 seconds of running.

I don't want While loop or any kind of loop to be used and would like to use IF-ELSE conditions instead as it would make it easier for me in my code.

The part of code I want to stop being executed after 15 seconds is a FOR loop itself. Let's consider the below code for example:

for (int i = 1; i < 100000; i++)
{
    Console.WriteLine("This is test no. "+ i+ "\n");
}

How would you stop this loop after 15 seconds of running?

You can assign DateTime variable before the loop having the current date and time, then in each loop iteration simply check if 15 seconds have passed:

DateTime start = DateTime.Now;
for (int i = 1; i < 100000; i++)
{
    if ((DateTime.Now - start).TotalSeconds >= 15)
        break;
    Console.WriteLine("This is test no. "+ i+ "\n");
}

Update: while the above will usually work, it's not bullet proof and might fail on some edge cases (as Servy pointed out in a comment ), causing endless loop. Better practice would be using the Stopwatch class, which is part of System.Diagnostics namespace:

Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 1; i < 100000; i++)
{
    if (watch.Elapsed.TotalMilliseconds >= 500)
        break;
    Console.WriteLine("This is test no. " + i + "\n");
}
watch.Stop();

I'm posting my answer from my older post because it's more relevant here,

I think you need to measure time and stop the code after particular time say "15 seconds" , StopWatch class can help you out.

// Create new stopwatch instance
Stopwatch stopwatch = new Stopwatch();
// start stopwatch
stopwatch.Start();
// Stop the stopwatch
stopwatch.Stop();
// Write result
Console.WriteLine("Time elapsed: {0}",stopwatch.Elapsed);
// you can check for Elapsed property when its greater than 15 seconds 
//then stop the code

Elapsed property returns TimeSpan instance you would do something like this.

TimeSpan timeGone = stopwatch.Elapsed;

To fit your scenario you can do something like this

Stopwatch stopwatch = new Stopwatch();
TimeSpan timeGone;
// Use TimeSpan constructor to specify:
// ... Days, hours, minutes, seconds, milliseconds.
// ... The TimeSpan returned has those values.
TimeSpan RequiredTimeLine = new TimeSpan(0, 0, 0, 15, 0);//set to 15 sec

While ( timeGone.Seconds < RequiredTimeLine.Seconds )
{
    stopwatch.Start();
    Start();
    timeGone = stopwatch.Elapsed;
}
Stop();//your method which will stop listening

Some useful links
MSDN StopWatch

更好的是你可以使用下面的代码,这将有助于提高性能。

System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM