Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

c# - 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+ "
");
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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+ "
");
}

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 + "
");
}
watch.Stop();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...