仅使用Timer一次
我想在主表单初始化后的1秒内只使用一次计时器。 我认为以下会有一个消息框说“Hello World”只有一次,但实际上每隔一秒就会出现一个新的消息框“Hello World”。
为什么这样? 我把t.Stop()
放在了tick事件中。 另外,我是否需要以某种方式处理计时器以避免内存泄漏?
Timer t = new Timer(); t.Interval = 1000; t.Tick += delegate(System.Object o, System.EventArgs e) { MessageBox.Show("Hello World"); t.Stop(); }; t.Start();
请帮助并显示是否有更好的方法吗? 谢谢。
替换MessageBox.Show("Hello World"); t.Stop();
MessageBox.Show("Hello World"); t.Stop();
with t.Stop();MessageBox.Show("Hello World");
。 因为您没有及时按OK,计时器已经再次打勾并且您从未到达停止代码。
把t.Stop();
在MessageBox.Show("Hellow World");
之前MessageBox.Show("Hellow World");
您也可以使用System.Timers.Timer并将AutoReset设置为false来实现此目的。 我正在研究使用哪个计时器,而不喜欢这个计时器,因为它不需要单独的stop命令。
using System; using System.IO; using System.Timers; System.Timers.Timer t = new System.Timers.Timer() { Interval = 1000, AutoReset = false }; t.Elapsed += delegate(System.Object o, System.Timers.ElapsedEventArgs e) { Console.WriteLine("Hell");}; t.Start();