我知道有三个Timer
个类,System.Threading.Timer
,System.Timers.Timer
和System.Windows.Forms.Timer
,但这些类都没有.Reset()
个功能将当前经过的时间重置为0.
是否有具有此功能的BCL类?这样做有非破解方法吗? (我想也许改变它的时间限制可能会重置它)想想重新实现具有此功能的Timer
类,或者如何使用其中一个BCL类可靠地执行它?/ p>
答案 0 :(得分:134)
我总是......
myTimer.Stop();
myTimer.Start();
......那是一个黑客? :)
每条评论,关于Threading.Timer,它是Change method ...
dueTime类型:
System.Int32
延迟之前的时间 调用指定的回调方法 当Timer被构造时,in 毫秒。指定Timeout.Infinite
以防止 计时器重启。指定零 (0)立即重启计时器。
答案 1 :(得分:54)
除System.Threading.Timer外,所有计时器都具有Start()和Stop()方法。
所以扩展方法如...
public static void Reset(this Timer timer)
{
timer.Stop();
timer.Start();
}
......是一种解决方法。
答案 2 :(得分:23)
对于System.Timers.Timer
,根据MSDN文档,http://msdn.microsoft.com/en-us/library/system.timers.timer.enabled.aspx:
如果在定时器启动后设置了间隔,则计数为 重启。例如,如果将间隔设置为5秒然后设置 Enabled属性为true,计数从Enabled时开始 组。如果在计数为3秒时将间隔重置为10秒, Elapsed事件在13秒后第一次被提升 Enabled设置为true。
所以,
const double TIMEOUT = 5000; // milliseconds
aTimer = new System.Timers.Timer(TIMEOUT);
aTimer.Start(); // timer start running
:
:
aTimer.Interval = TIMEOUT; // restart the timer
答案 3 :(得分:6)
您可以编写名为Reset()的扩展方法,
答案 4 :(得分:4)
我刚为计时器分配了一个新值:
mytimer.Change(10000, 0); // reset to 10 seconds
它适用于我。
代码顶部的定义了计时器:System.Threading.Timer myTimer;
if (!active)
{
myTimer= new System.Threading.Timer(new TimerCallback(TimerProc));
}
myTimer.Change(10000, 0);
active = true;
private void TimerProc(object state)
{
// The state object is the Timer object.
System.Threading.Timer t = (System.Threading.Timer)state;
t.Dispose();
Console.WriteLine("The timer callback executes.");
active = false;
//action to do when timer is back to zero
}
答案 5 :(得分:3)
为清晰起见,由于其他一些评论不正确,因此在使用System.Timers
设置时启用将重置已用时间。我刚用以下方法测试了行为:
Timer countDown= new Timer(3000);
Main()
{
TextBox.TextDidChange += TextBox_TextDidChange;
countdown.Elapsed += CountDown_Elapsed;
}
void TextBox_TextDidChange(Object sender, EventArgs e)
{
countdown.Enabled = true;
}
void CountDown_Elapsed(object sender, EventArgs e)
{
System.Console.WriteLine("Elapsed");
}
我会重复输入文本到文本框,定时器只会在最后一次击键后3秒运行。它也会在文档中暗示,正如您所见:调用Timers.Start()
只需将Enabled设置为true。
可以肯定的是,我应该从头开始直接进入,你会在.NET reference source中看到,如果启用已启用的计时器,它会调用私有UpdateTimer()
方法,内部调用Change()
。
答案 6 :(得分:2)
对于Timer(System.Windows.Forms.Timer)。
.Stop,然后.Start方法用作重置。
答案 7 :(得分:1)
重置windows.timer的其他替代方法是使用计数器,如下所示:
int tmrCtr = 0;
Timer mTimer;
private void ResetTimer()
{
tmrCtr = 0;
}
private void mTimer_Tick()
{
tmrCtr++;
//perform task
}
因此,如果您打算每1秒重复一次,可以将定时器间隔设置为100ms,并将计数器测试为10个周期。
如果计时器应该等待某些可能在不同时间段结束的进程,这是合适的。
答案 8 :(得分:1)
我这样做
//Restart the timer
queueTimer.Enabled = true;
答案 9 :(得分:1)
您可以执行timer.Interval = timer.Interval