停止15秒后运行代码 [英] Stop running the code after 15 seconds

查看:140
本文介绍了停止15秒后运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写点东西停止运行运行15秒后的代码。

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

我不希望循环或其他类型的循环中使用,并想用IF-ELSE条件,而不是因为它会在我的代码更适合我。

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.

我想停止15秒后执行代码的部分是一个FOR循环本身。让我们考虑,例如下面的代码:

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

您将如何运行15秒后停止这种循环?

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

推荐答案

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

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



更​​新:虽然上面通常会工作,它不是防弹,并可能失败一些边缘情况(如Servy在评论中指出 ),造成无端环。更好的做法是使用秒表类,这是的 System.Diagnostics程序的命名空间部分:

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

这篇关于停止15秒后运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆