C# 仅使用计时器一次

C# 仅使用计时器一次,c#,winforms,timer,C#,Winforms,Timer,我只想在主窗体初始化后1秒使用计时器一次。 我原以为下面会有一个消息框只显示一次“Hello World”,但实际上每一秒都会有一个新的消息框显示一次“Hello World” 为什么会这样?我在滴答声事件中放入了t.Stop()。 另外,我是否需要以某种方式处理计时器以避免内存泄漏 Timer t = new Timer(); t.Interval = 1000; t.Tick += delegate(System

我只想在主窗体初始化后1秒使用计时器一次。 我原以为下面会有一个消息框只显示一次“Hello World”,但实际上每一秒都会有一个新的消息框显示一次“Hello World”

为什么会这样?我在滴答声事件中放入了
t.Stop()
。 另外,我是否需要以某种方式处理计时器以避免内存泄漏

        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(“你好世界”);t、 停止()带有
t.Stop();MessageBox.Show(“你好世界”)。因为您没有及时按OK,计时器已经再次滴答作响,您从未到达停止代码。

Put
t.stop()MessageBox.Show(“Hellow World”)之前的code>

您也可以使用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();

好的,行了。谢谢但逻辑是什么?为什么顺序很重要?@zaidwaqi:线程进入MessageBox.Show方法,直到你按下OK才离开。但是你按下OK键的速度不够快,而且它已经打开了一个新的消息框。哦:)处理计时器怎么样?由于计时器不再使用,是否需要它?@zaidwaqi,你可以在t.Stop()之后调用t.Dispose()@SebastianGodelet只要他不再需要它,他可能无论如何都应该这样做。