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

use*_*819 7 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();
}
Run Code Online (Sandbox Code Playgroud)

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

jor*_*orx 23

使用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();
Run Code Online (Sandbox Code Playgroud)

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

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


Mat*_*nts 10

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

Task.Delay(TimeSpan.FromMilliseconds(2000))
    .ContinueWith(task => MessageBox.Show("fsdfs"));
Run Code Online (Sandbox Code Playgroud)

  • 到目前为止,这比计时器要好。 (2认同)

Jen*_*ter 6

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

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