gpt4 book ai didi

c# - 为什么 Windows.Forms.Timer 的间隔会随着滴答声的增加而减少?

转载 作者:行者123 更新时间:2023-11-30 22:13:11 24 4
gpt4 key购买 nike

我写了一个简单的程序,它使用定时器淡出标签。我发现定时器太不精确了,间隔越来越短。

下面的代码证明了我的想法:
(我也是用 StopWatch 实现的。刻度之间的间隔几乎相等。)


private void timer1_Tick(object sender, EventArgs e)
{
elapsed += timer1.Interval;
timerTest.AppendText(DateTime.UtcNow.Second.ToString() + "." + DateTime.UtcNow.Millisecond.ToString() + "\r\n");
if (elapsed >= target)
timer1.Stop();
}<br/>
int elapsed = 0;
int target = 4000;<br/>
private void button_Click(object sender, EventArgs e)
{
labelFadeout.ForeColor = Color.Greed;
elapsed = 0;
timer1.Interval = 100;
timer1.Tick += timer1_Tick;
timer1.Start();
}

第 1 和第 5 输出导致差异!


[1st] [5th]
20.318 42.955
20.377 42.956
20.491 42.957
20.595 42.958
20.707 42.959
20.814 43.68
20.929 43.69
21.34 43.7
21.142 43.71
21.257 43.72
21.365 43.173
21.471 43.176
21.584 43.177
21.692 43.179
21.8 43.18
21.909 43.286
22.19 43.288
22.127 43.289
22.242 43.291
22.347 43.293
22.454 43.397
22.569 43.4
22.673 43.402
22.784 43.404
22.892 43.406
23.4 43.649
23.112 43.652
23.221 43.655
23.331 43.657
23.494 43.66
23.549 43.746
23.662 43.749
23.779 43.751
23.879 43.754
23.991 43.756
24.95 43.846
24.209 43.848
24.316 43.851
24.427 43.853
24.534 43.855

我检查过

并且仍然很好奇它怎么会如此不精确。谁能解释一下??

最佳答案

您测试间隔的方法已关闭。您实际上只是每隔一段时间获取当前时间的一部分,并期望它与您上次获取的时间相当。

如果您想测试计时器以 100 为间隔真正花费多少时间。使用实际的秒表,并查看它的Elapsed 以了解过去了多少时间。

Stopwatch stopwatch = new Stopwatch();
int elapsed = 0;
int target = 4000;

private void timer1_Tick(object sender, EventArgs e)
{
elapsed += timer1.Interval;
timerTest.AppendText(stopwatch.Elapsed.TotalSeconds.ToString());
stopwatch.Restart();

if (elapsed >= target)
timer1.Stop();
}

private void button1_Click(object sender, EventArgs e)
{
elapsed = 0;
timer1.Interval = 100;
timer1.Tick += timer1_Tick;
stopwatch.Start();
timer1.Start();
}

我的结果:

0.1055445
0.0872668
0.1121169
0.1032453
0.1066107
0.1097218
0.103818
0.1079014
...

关于c# - 为什么 Windows.Forms.Timer 的间隔会随着滴答声的增加而减少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19318944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com