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

12

我希望在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个回答

33

关于计时器之间的差异,请参考 https://dev59.com/nW855IYBdhLWcg3wGQXY#4532859 - Developer Marius Žilėnas

17

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

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

2
这绝对比计时器更好。 - Don Rolling
1
如果你的目标是 .NET 4.0,那么请使用 System.Threading.Tasks.TaskEx 替代 Task。详情请参考:https://dev59.com/m1sW5IYBdhLWcg3wX2Zz#35041622 - OneWorld

7
尝试在计时器进入Tick时立即停止计时器:
timer.Tick += (s, e) => 
{ 
  ((System.Windows.Forms.Timer)s).Stop(); //s is the Timer
  action(); 
};

AutoReset是更好的解决方案。 - Jared Beach

0

添加

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

之后

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

0
timer.Dispose() 放在 Tick 方法中的 action 之前(如果该操作等待用户响应,例如您的 MessageBox,则计时器将一直运行,直到用户响应为止)。
timer.Tick += (s, e) => { timer.Dispose(); action(); };

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;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接