15秒后停止运行代码

我正在尝试写一些东西,以便在运行15秒后停止运行代码。

我不希望使用While循环或任何类型的循环,并希望使用IF-ELSE条件,因为它会使我在我的代码中更容易。

我希望在15秒后停止执行的代码部分是FOR循环本身。 我们考虑以下代码:

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

如何在运行15秒后停止此循环?

您可以在具有当前日期和时间的循环之前分配DateTime变量,然后在每个循环迭代中只检查是否已经过了15秒:

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

更新:虽然上面通常会起作用,但它不是防弹的,并且可能在某些边缘情况下失败(正如Servy 在评论中指出的那样),导致无限循环。 更好的做法是使用Stopwatch类,它是System.Diagnostics命名空间的一部分:

 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(); 

我是从我的旧post发布我的答案,因为它在这里更相关,

我认为你需要在特定时间说“15秒”之后测量时间并停止代码, StopWatch类可以帮助你。

 // 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属性返回TimeSpan实例,你会做这样的事情。

 TimeSpan timeGone = stopwatch.Elapsed; 

为了适应您的场景,您可以执行类似的操作

 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 

一些有用的链接
MSDN StopWatch

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

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