【发布时间】:2018-05-29 05:01:23
【问题描述】:
我想在 C# 中定期检查 60 秒。我可以通过定期检查日期来做到这一点,如下所示
但是,当我使用秒表时,秒表会重置回起点,而不是从上次停止秒表时继续。
using System;
using System.Diagnostics;
using System.Threading;
namespace StopwatchExample
{
class Program
{
static void Main()
{
////Works
//DateTime start = DateTime.Now;
//while (true)
//{
// DateTime current = DateTime.Now;
// var diffInSeconds = (current - start).TotalSeconds;
// if (diffInSeconds > 5)
// {
// Console.WriteLine("5 s done!");
// break;
// }
//}
// Does not work
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (true)
{
stopwatch.Stop();
if (stopwatch.Elapsed.Seconds > 5)
{
Console.WriteLine("5 s done!");
break;
}
else
{
stopwatch.Start();
}
}
Console.ReadLine();
}
}
}
【问题讨论】:
-
您无需停止秒表即可读取其当前值。
-
另外,这看起来像是
Timer的工作,而不是StopWatch或DateTime -
请写清楚您的要求。你想每隔 60 多岁就重复做一项任务吗?
-
请写清楚您的要求。我们无法理解您的问题。
-
您正在运行一个非常频繁地运行的循环并检查已用时间。你最好使用
Thread.Sleep(5000)而不是你所有的代码。