C# 定时器间隔 1000 != 1 秒?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14395700/
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-10 11:42:04  来源:igfitidea点击:

Timer Interval 1000 != 1 second?

c#timerseconds

提问by Tim Kathete Stadler

I have a label which should show the seconds of my timer (or in other word I have a variable to which is added 1 every interval of the timer). The interval of my timer is set to 1000, so the label should update itself every second (and should also show the seconds). But the label is after 1 second already in the hundreds. What is a proper interval to get 1 second?

我有一个标签,它应该显示我的计时器的秒数(或者换句话说,我有一个变量,每个计时器间隔都加 1)。我的计时器的间隔设置为 1000,因此标签应该每秒更新一次(并且还应该显示秒数)。但是标签在 1 秒后已经有数百个了。获得 1 秒的适当间隔是多少?

int _counter = 0;
Timer timer;

timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(TimerEventProcessor);
label1.Text = _counter.ToString();
timer.Start();

private void TimerEventProcessor(object sender, EventArgs e)
{
  label1.Text = _counter.ToString();
  _counter += 1;
}

采纳答案by Guffa

The proper interval to get one second is 1000. The Intervalproperty is the time between ticks in milliseconds:

获取一秒的正确间隔是 1000。该Interval属性是以毫秒为单位的滴答之间的时间:

MSDN: Timer.Interval Property

MSDN:Timer.Interval 属性

So, it's not the interval that you set that is wrong. Check the rest of your code for something like changing the interval of the timer, or binding the Tickevent multiple times.

所以,不是你设置的间隔是错误的。检查代码的其余部分,例如更改计时器的间隔或Tick多次绑定事件。

回答by daryal

Instead of Tickevent, use Elapsedevent.

Tick使用Elapsed事件代替事件。

timer.Elapsed += new EventHandler(TimerEventProcessor);

and change the signiture of TimerEventProcessor method;

并更改 TimerEventProcessor 方法的签名;

private void TimerEventProcessor(object sender, ElapsedEventArgs e)
{
  label1.Text = _counter.ToString();
  _counter += 1;
}

回答by peterchen

Any other places you use TimerEventProcessor or Counter?

您使用 TimerEventProcessor 或 Counter 的任何其他地方?

Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.

无论如何,您不能依赖每秒准确传递一个事件。时间可能会有所不同,系统不会确保平均时间正确。

So instead of _Counter, you should use:

所以,而不是 _Counter,你应该使用:

 // when starting the timer:
 DateTime _started = DateTime.UtcNow;

 // in TimerEventProcessor:
 seconds = (DateTime.UtcNow-started).TotalSeconds;
 Label.Text = seconds.ToString();


Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.

注意:这并不能解决TimerEventProcessor被频繁调用,或者_Counter自增到频繁的问题。它只是掩盖它,但它也是正确的方法。