我有一个C#程序,在这个程序中,如果用户停止与程序交互,我需要计时器停止。它需要做的是暂停,然后在用户再次变为活动状态时重新启动。我做了一些研究,发现有这样的命令:
timer.Stop();
和
timer.Start();
但我想知道有没有这样的:
timer.Pause();
然后,当用户再次变为活动状态时,它会从停止的位置重新开始,并且不会重新启动。如果有人能帮上忙,我将不胜感激!谢谢,
弥卡
发布于 2014-11-17 09:36:52
这可以通过使用.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();
发布于 2018-06-13 06:28:20
我已经为这种情况创建了这个类:
public 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();
}
}
发布于 2014-11-17 10:24:58
没有停顿,因为很容易做同样的事情。你可以停止计时器而不是暂停它,然后当你需要重新启动它时,你只需要指定剩余的时间量。它可能很复杂,也可能很简单;这取决于您使用计时器做什么。事实上,你做什么取决于你使用计时器做什么,这可能是暂停不存在的原因。
您可能正在使用计时器在固定的时间段重复做某事,或者您可能正在使用计时器倒计时到特定的时间。如果您正在重复做某事(例如每秒),那么您的要求可能是在该时间段的开始(一秒)或该时间段的一部分重新启动。如果暂停的时间超过该时间段,会发生什么?通常,遗漏的事件会被忽略,但这取决于需求。
所以我想说的是,你需要确定你的需求。然后,如果你需要帮助,那就澄清你需要什么。
https://stackoverflow.com/questions/26964192
复制相似问题