如何在 C# 中重置计时器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1042312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:49:21  来源:igfitidea点击:

How to reset a timer in C#?

c#timer

提问by Matthew Scharley

There are three Timerclasses that I am aware of, System.Threading.Timer, System.Timers.Timer, and System.Windows.Forms.Timer, but none of these have a .Reset()function which would reset the current elapsed time to 0.

Timer我知道三个类System.Threading.TimerSystem.Timers.Timer, 和System.Windows.Forms.Timer,但这些类都没有.Reset()将当前经过时间重置为 0的函数。

Is there a BCL class that has this functionality? Is there a non-hack way of doing it? (I thought perhaps changing the time limit on it might reset it) Thought on how hard it would be to reimplement a Timerclass that had this functionality, or how to do it reliably with one of the BCL classes?

是否有具有此功能的 BCL 类?有没有一种非黑客的方式来做到这一点?(我想也许改变它的时间限制可能会重置它)想过重新实现一个Timer具有此功能的类会有多困难,或者如何使用 BCL 类之一可靠地实现它?

采纳答案by JP Alioto

I always do ...

我经常做 ...

myTimer.Stop();
myTimer.Start();

... is that a hack? :)

......这是一个黑客?:)

Per comment, on Threading.Timer, it's the Change method...

根据评论,在 Threading.Timer 上,它是Change 方法......

dueTime Type: System.Int32The amount of time to delay before the invoking the callback method specified when the Timer was constructed, in milliseconds. Specify Timeout.Infiniteto prevent the timer from restarting. Specify zero (0) to restart the timer immediately.

DueTime 类型:System.Int32在调用构造 Timer 时指定的回调方法之前延迟的时间量,以毫秒为单位。指定 Timeout.Infinite以防止计时器重新启动。指定零 (0) 可立即重新启动计时器。

回答by Dan

All the timers have the equivalent of Start() and Stop() methods, except System.Threading.Timer.

除了 System.Threading.Timer 之外,所有计时器都具有等效的 Start() 和 Stop() 方法。

So an extension method such as...

所以一个扩展方法,比如...

public static void Reset(this Timer timer)
{
  timer.Stop();
  timer.Start();
}

...is one way to go about it.

...是一种方法。

回答by Gishu

You could write an extension method called Reset(), which

您可以编写一个名为 Reset() 的扩展方法,它

  • calls Stop()-Start() for Timers.Timer and Forms.Timer
  • calls Change for Threading.Timer
  • 为 Timers.Timer 和 Forms.Timer 调用 Stop()-Start()
  • 为 Threading.Timer 调用 Change

回答by ivan

Other alternative way to reset the windows.timer is using the counter, as follows:

重置 windows.timer 的其他替代方法是使用计数器,如下所示:

int tmrCtr = 0;
Timer mTimer;

private void ResetTimer()
{
  tmrCtr = 0;
}

private void mTimer_Tick()
{
  tmrCtr++;
  //perform task
}  

So if you intend to repeat every 1 second, you can set the timer interval at 100ms, and test the counter to 10 cycles.

所以如果你打算每1秒重复一次,你可以将定时器间隔设置为100ms,并将计数器测试为10个周期。

This is suitable if the timer should wait for some processes those may be ended at the different time span.

如果计时器应该等待可能在不同时间跨度结束的某些进程,则这是合适的。

回答by elmsoftware

For a Timer (System.Windows.Forms.Timer).

对于计时器 (System.Windows.Forms.Timer)。

The .Stop, then .Start methods worked as a reset.

.Stop 和 .Start 方法作为重置工作。

回答by mMontu

For System.Timers.Timer, according to MSDN documentation, http://msdn.microsoft.com/en-us/library/system.timers.timer.enabled.aspx:

对于System.Timers.Timer,根据 MSDN 文档,http: //msdn.microsoft.com/en-us/library/system.timers.timer.enabled.aspx

If the interval is set after the Timer has started, the count is reset. For example, if you set the interval to 5 seconds and then set the Enabled property to true, the count starts at the time Enabled is set. If you reset the interval to 10 seconds when count is 3 seconds, the Elapsed event is raised for the first time 13 seconds after Enabled was set to true.

如果在计时器启动后设置了间隔,则计数将被重置。例如,如果您将间隔设置为 5 秒,然后将 Enabled 属性设置为 true,则从设置为 Enabled 的时间开始计数。如果在计数为 3 秒时将间隔重置为 10 秒,则 Elapsed 事件会在 Enabled 设置为 true 后 13 秒首次引发。

So,

所以,

    const double TIMEOUT = 5000; // milliseconds

    aTimer = new System.Timers.Timer(TIMEOUT);
    aTimer.Start();     // timer start running

    :
    :

    aTimer.Interval = TIMEOUT;  // restart the timer

回答by Quispie

I just assigned a new value to the timer:

我刚刚为计时器分配了一个新值:

mytimer.Change(10000, 0); // reset to 10 seconds

it works fine for me.

这对我来说可以。

at the top of the code define the timer: System.Threading.Timer myTimer;

在代码顶部定义计时器: 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
    }

回答by Rissa

i do this

我这样做

//Restart the timer
queueTimer.Enabled = true;

回答by Ella Sharakanski

You can do timer.Interval = timer.Interval

你可以做 timer.Interval = timer.Interval

回答by NickSpag

For clarity since some other comments are incorrect, when using System.Timerssetting Enabled to true willreset the elapsed time. I just tested the behavior with the below:

为了清楚起见,因为其他一些注释是不正确的,当使用System.Timers设置 Enabled 为 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");
}

I would input text to the text box repeatedly and the timer would only run 3 seconds after the last keystroke. It's hinted at in the docs as well, as you'll see: calling Timers.Start()simply sets Enabled to true.

我会反复向文本框输入文本,并且计时器只会在最后一次击键后运行 3 秒。正如您将看到的,文档中也暗示了这一点:调用Timers.Start()只是将 Enabled 设置为 true。

And to be sure, which I should've just went straight to from the beginning, you'll see in the .NET reference sourcethat if enabling an already Enabled timer it calls the private UpdateTimer()method, which internally calls Change().

可以肯定的是,我应该从一开始就直接进入,您将在.NET 参考源中看到,如果启用已启用的计时器,它将调用私有UpdateTimer()方法,该方法在内部调用Change().