如何只在C#中运行一次计时器?

时间:2013-05-30 05:01:41

标签: c#

我希望C#中的计时器在执行后自行销毁。我怎么能实现这个目标?

private void button1_Click(object sender, EventArgs e)
{
    ExecuteIn(2000, () =>
    {
        MessageBox.Show("fsdfs");   
    });           
}

public static void ExecuteIn(int milliseconds, Action action)
{
    var timer = new System.Windows.Forms.Timer();
    timer.Tick += (s, e) => { action(); };
    timer.Interval = milliseconds;
    timer.Start();

    //timer.Stop();
}

我希望此消息框只显示一次。

6 个答案:

答案 0 :(得分:19)

使用Timer.AutoReset属性:
https://msdn.microsoft.com/en-us/library/system.timers.timer.autoreset(v=vs.110).aspx

即:

System.Timers.Timer runonce=new System.Timers.Timer(milliseconds);
runonce.Elapsed+=(s, e) => { action(); };
runonce.AutoReset=false;
runonce.Start();

就我而言,在Tick方法中停止或处理Timer是不稳定的

编辑:这不适用于System.Windows.Forms.Timer

答案 1 :(得分:8)

我最喜欢的技巧就是这样做......

Task.Delay(TimeSpan.FromMilliseconds(2000))
    .ContinueWith(task => MessageBox.Show("fsdfs"));

答案 2 :(得分:6)

尝试在进入Tick时停止计时器:

timer.Tick += (s, e) => 
{ 
  ((System.Windows.Forms.Timer)s).Stop(); //s is the Timer
  action(); 
};

答案 3 :(得分:0)

添加

timer.Tick += (s, e) => { timer.Stop() };

之后

timer.Tick += (s, e) => { action(); };

答案 4 :(得分:0)

timer.Dispose()放在操作之前的Tick方法中(如果操作等待用户的respose,即你的MessageBox,那么计时器将继续直到他们回复了。)

timer.Tick += (s, e) => { timer.Dispose(); action(); };

答案 5 :(得分:0)

在Intializelayout()中写下这个。

this.timer1 = new System.Windows.Forms.Timer(this.components);
this.timer1.Enabled = true;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);

并在表单代码中添加此方法

private void timer1_Tick(object sender, EventArgs e)
    {
        doaction();
        timer1.Stop();
        timer1.Enabled = false;
    }
相关问题