【发布时间】:2014-02-04 11:57:02
【问题描述】:
我正在编写一个简单的 C# 程序,它尝试使用 System.Forms.Timer 每 x 秒执行一次操作
tick 事件调用一个方法来启动一个新线程并禁用计时器,然后当线程完成它的工作时,它会再次启用计时器,但问题是,现在它在启用后不会滴答作响.
static System.Windows.Forms.Timer testtimer = new System.Windows.Forms.Timer();
static void Main()
{
testtimer.Tick += testtimertick;
testtimer.Interval = 5000;
testtimer.Enabled = true;
testtimer.Start();
while (true)
{
Application.DoEvents(); //Prevents application from exiting
}
}
private static void testtimertick(object sender, System.EventArgs e)
{
testtimer.Enabled = false;
Thread t = new Thread(dostuff);
t.Start();
}
private static void dostuff()
{
//Executes some code
testtimer.Enabled = true; //Re enables the timer but it doesn't work
testtimer.Start();
}
【问题讨论】:
-
只是为了在这里确认您的意图;您希望计时器触发,然后在
dostuff()方法完成之前不触发? -
是的,确切地说,当 dostuff 没有完成时,计时器不应该启动。
-
您是否尝试过
timer.Stop(),然后在准备就绪时尝试timer.Start()?我也不太确定 Timer 是否是线程安全类,所以请检查this post out -
testTimer.Enabled = true;相当于 testTimer.start();见:stackoverflow.com/questions/1012948/…
标签: c# multithreading timer