我写了一个简单的程序,它使用计时器来淡出标签。我发现计时器太不精确了,间隔越来越短。
下面的代码证明了我的想法:(
我也是用 StopWatch 实现的,tick 之间的间隔几乎相等。)
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();
}
int elapsed = 0;
int target = 4000;
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
我已经检查过了
并且仍然好奇它怎么会如此不精确。任何人都可以解释这个?