如何在C#中只运行一次计时器?
我想要一个C#中的计时器,一旦执行,它就会自我毁灭。我怎样才能做到这一点如何在C#中只运行一次计时器?,c#,C#,我想要一个C#中的计时器,一旦执行,它就会自我毁灭。我怎样才能做到这一点 private void button1_Click(object sender, EventArgs e) { ExecuteIn(2000, () => { MessageBox.Show("fsdfs"); }); } public static void ExecuteIn(int milliseconds, Action action)
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();
}
我希望此消息框仅显示一次。添加
timer.Tick += (s, e) => { timer.Stop() };
之后
timer.Tick += (s, e) => { action(); };
尝试在计时器进入滴答声时立即停止计时器:
timer.Tick += (s, e) =>
{
((System.Windows.Forms.Timer)s).Stop(); //s is the Timer
action();
};
将timer.Dispose()放在操作之前的Tick方法中(如果操作等待用户的响应,即您的MessageBox,则计时器将继续,直到用户响应为止)
在initializeLayout()中编写以下内容
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;
}
使用Timer.AutoReset属性:
i、 e:
System.Timers.Timer runonce=新系统.Timers.Timer(毫秒);
runonce.appead+=(s,e)=>{action();};
runonce.AutoReset=false;
runonce.Start();
就我而言,在Tick方法中停止或处理计时器是不稳定的
编辑:这不适用于System.Windows.Forms.Timer我最喜欢的技术是这样做
Task.Delay(TimeSpan.FromMilliseconds(2000))
.ContinueWith(task => MessageBox.Show("fsdfs"));
到目前为止,这比计时器要好。如果您的目标是.NET 4.0 AutoReset,则使用
System.Threading.Tasks.TaskEx
而不是Task
更好地解决计时器之间的差异
Task.Delay(TimeSpan.FromMilliseconds(2000))
.ContinueWith(task => MessageBox.Show("fsdfs"));