C# 在C中使用秒表定期检查5秒钟#
我想定期检查C#中的60秒。我能做到这一点,定期检查日期如下 但是,当我使用秒表时,秒表会重置回开始位置,而不是从上一次秒表停止时继续C# 在C中使用秒表定期检查5秒钟#,c#,stopwatch,C#,Stopwatch,我想定期检查C#中的60秒。我能做到这一点,定期检查日期如下 但是,当我使用秒表时,秒表会重置回开始位置,而不是从上一次秒表停止时继续 using System; using System.Diagnostics; using System.Threading; namespace StopwatchExample { class Program { static void Main() { ////Works
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();
}
}
}
尝试使用计时器(System.Timers)代替秒表。
设置所需的时间间隔,并对经过的事件执行必要的操作
你可以找到更多
例如:
public static void Main()
{
// Create a timer and set a two second interval.
aTimer = new System.Timers.Timer();
aTimer.Interval = 2000; // 2000ms == 2s
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
// Have the timer fire repeated events (true is the default)
aTimer.AutoReset = true;
// Start the timer
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
}
private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine("The interval has been elapsed");
}
正如其他人所说,定时器可能是更好的解决方案。鉴于您使用了秒表,您需要将逻辑更改为:
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (true)
{
// Check elapsed time w/o stopping/resetting the stopwatch
// May want to include the 5 seconds themselves (>= instead of >)
if (stopwatch.Elapsed.Seconds >= 5)
{
// At least 5 seconds elapsed, restart stopwatch.
stopwatch.Stop();
stopwatch.Start();
Console.WriteLine("5 s done!");
// Not sure about this, if you really want to check "periodically",
// this break makes less sense, because the checking
// logic will stop after the first 5 seconds have elapsed.
break;
}
}
您不必停止秒表读取其当前值。此外,这看起来像是一个
计时器的作业,而不是秒表或日期时间
。请清楚地写下您的要求。你想每隔60秒重复做一项任务吗?请写清楚你的要求。我们无法理解您的问题。您正在运行一个非常频繁的循环并检查所用的时间。你最好使用Thread.Sleep(5000)
而不是所有的代码。