只使用一次定时器 [英] Using Timer only once
问题描述
我只想在主窗体初始化后 1 秒使用一次计时器.我以为下面会有一个消息框只说一次Hello World",但实际上每秒钟都会有一个新的消息框说Hello World".
I want to use a timer only once, at 1 second after the initialization of my main form. I thought the following would have a message box saying "Hello World" just once, but actually a new message box says "Hello World" every one second.
为什么会这样?我已经把 t.Stop()
放在滴答事件中.另外,我是否需要以某种方式处理计时器以避免内存泄漏?
Why so? I had put t.Stop()
in the tick event.
Also, do I need to dispose the timer somehow to avoid memory leakage?
Timer t = new Timer();
t.Interval = 1000;
t.Tick += delegate(System.Object o, System.EventArgs e)
{ MessageBox.Show("Hello World"); t.Stop(); };
t.Start();
请帮忙看看是否有更好的方法来做到这一点?谢谢.
Please help and show if there is a better way of doing this? Thanks.
推荐答案
Replace MessageBox.Show("Hello World");t.Stop();
和 t.Stop();MessageBox.Show("Hello World");
.因为你没有及时按下确定,计时器已经再次滴答滴答,你一直没有到达停止代码.
Replace MessageBox.Show("Hello World"); t.Stop();
with t.Stop();MessageBox.Show("Hello World");
. Because you're not pressing OK in time, the timer has already ticked again and you never reached the stop code.
这篇关于只使用一次定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!