我知道有三个与Timer
相关的类:System.Threading.Timer
、System.Timers.Timer
和System.Windows.Forms.Timer
,但是它们都没有一个.Reset()
函数,可以将当前经过的时间重置为0。
是否有BCL类具备此功能呢?是否有非hack方式实现此功能呢?(我认为也许改变时间限制可能会重置它)是否考虑重新实现一个带有此功能的Timer
类,或者如何在BCL类之一中可靠地实现此功能?
我知道有三个与Timer
相关的类:System.Threading.Timer
、System.Timers.Timer
和System.Windows.Forms.Timer
,但是它们都没有一个.Reset()
函数,可以将当前经过的时间重置为0。
是否有BCL类具备此功能呢?是否有非hack方式实现此功能呢?(我认为也许改变时间限制可能会重置它)是否考虑重新实现一个带有此功能的Timer
类,或者如何在BCL类之一中可靠地实现此功能?
我经常使用以下代码来获取当前脚本的文件名:
myTimer.Stop();
myTimer.Start();
...那算不算是一个技巧呢? :)
根据评论,在Threading.Timer中,这是Change方法...
dueTime 类型:
System.Int32
在以毫秒为单位构造 Timer 时指定的回调方法被调用之前要延迟的时间量。指定Timeout.Infinite
以防止计时器重新启动。将其指定为零 (0) 以立即重新启动计时器。
除了System.Threading.Timer之外,所有计时器都具有Start()和Stop()方法的相当版本。
因此,可以使用扩展方法...
public static void Reset(this Timer timer)
{
timer.Stop();
timer.Start();
}
这是一种可行的方法。
timer.Start()
是不会起作用的。我写了这个Linqpad查询来测试它。试着把其中的 timer.Stop
移除,你就会看到区别。 - Jared Beach对于 System.Timers.Timer
,根据 MSDN 文档 http://msdn.microsoft.com/en-us/library/system.timers.timer.enabled.aspx:
如果在 Timer 启动之后设置间隔,则计数会被重置。例如,如果您将间隔设置为 5 秒,然后将 Enabled 属性设置为 true,则计数从 Enabled 设置的时间开始。如果您在计数为 3 秒时将间隔重置为 10 秒,则 Elapsed 事件将在启用为 true 的 13 秒后首次引发。
因此,
const double TIMEOUT = 5000; // milliseconds
aTimer = new System.Timers.Timer(TIMEOUT);
aTimer.Start(); // timer start running
:
:
aTimer.Interval = TIMEOUT; // restart the timer
你可以编写一个名为Reset()的扩展方法,它可以:
我刚刚给计时器分配了一个新值:
mytimer.Change(10000, 0); // 重置为10秒
对我来说它运行得很好。
在代码顶部定义计时器:System.Threading.Timer myTimer;
if (!active)
myTimer = new Timer(new TimerCallback(TimerProc));
myTimer.Change(10000, 0);
active = true;
private void TimerProc(object state)
{
// The state object is the Timer object.
var t = (Timer)state;
t.Dispose();
Console.WriteLine("The timer callback executes.");
active = false;
// Action to do when timer is back to zero
}
timer.Interval = timer.Interval
。对于计时器(System.Windows.Forms.Timer)。
.Stop,然后 .Start 方法可作为重置使用。
timer.Dispose();
timer = new System.Timers.Timer();
很抱歉回答晚了,但希望这个回答能对你有所帮助。
如果你需要一个“看门狗”式的计时器,可以使用System.Threading.Timer
类和Change
方法。
using System;
using System.Threading;
namespace WatchdogExample
{
internal class Watchdog
{
static void Main(string[] args)
{
Timer t = new Timer(timer_callback, null, 3000, Timeout.Infinite);
while (true)
{
Console.ReadLine();
t.Change(3000, Timeout.Infinite);
}
}
static void timer_callback(object state)
{
Console.WriteLine("test");
}
}
}
重置Windows计时器的另一种替代方法是使用计数器,具体如下:
int timerCtr = 0;
Timer mTimer;
private void ResetTimer() => timerCtr = 0;
private void mTimer_Tick()
{
timerCtr++;
// Perform task
}
所以如果您想要每1秒重复一次,您可以将定时器间隔设置为100毫秒,并测试计数器进行10个周期。
如果定时器应等待某些在不同时间跨度结束的进程,则此方法非常适用。
ctr
是什么。我猜它是 counter
,但即使如此,我也不知道它应该意味着什么。它是在计算滴答声的数量还是其他什么? - AustinWBryan