有三个Timer
类,我所知道的, System.Threading.Timer
, System.Timers.Timer
,和System.Windows.Forms.Timer
,但这些都没有一个.Reset()
这将重置当前的经过时间的功能为0。
是否有具有此功能的BCL类? 有没有做这件事的非黑客攻击方式吗? (我想也许改变的时间限制它可能会重置它)认为它会是多么困难重新实现Timer
类有这个功能,或者如何与BCL类之一可靠地做到这一点?
有三个Timer
类,我所知道的, System.Threading.Timer
, System.Timers.Timer
,和System.Windows.Forms.Timer
,但这些都没有一个.Reset()
这将重置当前的经过时间的功能为0。
是否有具有此功能的BCL类? 有没有做这件事的非黑客攻击方式吗? (我想也许改变的时间限制它可能会重置它)认为它会是多么困难重新实现Timer
类有这个功能,或者如何与BCL类之一可靠地做到这一点?
我经常做 ...
myTimer.Stop();
myTimer.Start();
...是一个黑客? :)
每评论,在Threading.Timer,它的更改方法 ...
duetime参数类型:
System.Int32
的时间量到调用当定时器构建,以毫秒为单位指定的回调方法之前延迟。 指定Timeout.Infinite
防止计时器重新启动。 指定零(0)立即重新启动计时器。
所有定时器有start()和stop()方法,除System.Threading.Timer的等价物。
因此,一个扩展方法,如...
public static void Reset(this Timer timer)
{
timer.Stop();
timer.Start();
}
......是去了解它的一种方式。
对于System.Timers.Timer
,根据MSDN文档, http://msdn.microsoft.com/en-us/library/system.timers.timer.enabled.aspx :
如果计时器启动后时间间隔设置,计数重。 例如,如果你设置的时间间隔为5秒,然后将Enabled属性设置为true,则开始计数,在启用设置的时间。 如果将时间间隔重置为10秒时数为3秒,经过事件引发首次启用经过13秒设置为true。
所以,
const double TIMEOUT = 5000; // milliseconds
aTimer = new System.Timers.Timer(TIMEOUT);
aTimer.Start(); // timer start running
:
:
aTimer.Interval = TIMEOUT; // restart the timer
你可以写一个扩展方法称为复位(),它
我只是分配一个新值定时器:
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
}
为了清楚起见,因为一些其他的评论是不正确的,使用时System.Timers
设置启用为true, 将重新经过的时间。 我刚刚测试了以下行为:
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()
简单地设置启用为true。
而且可以肯定,这是我应该刚刚直奔从一开始,你会在看到.NET参考源 ,如果让一个已经启用定时器,它调用私有UpdateTimer()
方法,它在内部调用Change()
。
对于一个定时器(System.Windows.Forms.Timer)。
该.Stop,然后。开始工作方法作为复位。
重置windows.timer其它替代方法是使用计数器,如下所示:
int tmrCtr = 0;
Timer mTimer;
private void ResetTimer()
{
tmrCtr = 0;
}
private void mTimer_Tick()
{
tmrCtr++;
//perform task
}
所以,如果你打算重复每1秒,你可以在100毫秒设置计时器的时间间隔和测试柜台10个周期。
这是合适的,如果计时器应该等待一段处理这些可以在不同的时间跨度结束。
我这样做
//Restart the timer
queueTimer.Enabled = true;
你可以做timer.Interval = timer.Interval