我有一个C#程序,在其中,如果用户停止与程序交互,我需要定时器停止。它需要暂停,然后在用户再次活动时重新启动。我做了一些研究,发现有诸如以下命令:
timer.Stop();
和
timer.Start();
但是我想知道是否有这样一个:
timer.Pause();
当用户再次活动时,应用程序会从离开的地方继续执行,而不是重新启动。如果有人能够帮忙,将不胜感激!
Micah
timer.Stop();
和
timer.Start();
但是我想知道是否有这样一个:
timer.Pause();
当用户再次活动时,应用程序会从离开的地方继续执行,而不是重新启动。如果有人能够帮忙,将不胜感激!
Micah
您可以通过在.NET中使用Stopwatch
类来实现此目的。仅需停止和启动即可继续使用秒表实例。
请确保使用using System.Diagnostics;
var timer = new Stopwatch();
timer.Start();
timer.Stop();
Console.WriteLine(timer.Elapsed);
timer.Start(); //Continues the timer from the previously stopped time
timer.Stop();
Console.WriteLine(timer.Elapsed);
要重置秒表,只需调用Reset
或Restart
方法,如下所示:
timer.Reset();
timer.Restart();
Reset
停止并重置计时器;Restart
也是一样,但它还会启动被重置的秒表。 - Stefanpublic class PausableTimer : Timer
{
public double RemainingAfterPause { get; private set; }
private readonly Stopwatch _stopwatch;
private readonly double _initialInterval;
private bool _resumed;
public PausableTimer(double interval) : base(interval)
{
_initialInterval = interval;
Elapsed += OnElapsed;
_stopwatch = new Stopwatch();
}
public new void Start()
{
ResetStopwatch();
base.Start();
}
private void OnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
if (_resumed)
{
_resumed = false;
Stop();
Interval = _initialInterval;
Start();
}
ResetStopwatch();
}
private void ResetStopwatch()
{
_stopwatch.Reset();
_stopwatch.Start();
}
public void Pause()
{
Stop();
_stopwatch.Stop();
RemainingAfterPause = Interval - _stopwatch.Elapsed.TotalMilliseconds;
}
public void Resume()
{
_resumed = true;
Interval = RemainingAfterPause;
RemainingAfterPause = 0;
Start();
}
}
Timer
类?为什么Stop()
方法不能满足你的需求?你不能稍后再调用Start()
吗? - Peter Duniho