2 回答

TA貢獻1801條經驗 獲得超16個贊
嘗試使用 Timer (System.Timers) 而不是 Stopwatch。設置所需的時間間隔并對 Elapsed 事件執行必要的操作。
在這里您可以了解更多信息。
例子:
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");
}

TA貢獻1829條經驗 獲得超7個贊
正如其他人所說, aTimer可能是更好的解決方案。鑒于您對 的使用Stopwatch,您需要將邏輯更改為:
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;
}
}
- 2 回答
- 0 關注
- 263 瀏覽
添加回答
舉報