gpt4 book ai didi

c# - 15 秒后停止运行代码

转载 作者:太空狗 更新时间:2023-10-30 00:03:16 27 4
gpt4 key购买 nike

我正在尝试编写一些代码以在运行 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 指出的 in a comment ),导致无限循环。更好的做法是使用 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();

关于c# - 15 秒后停止运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13218933/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com