我正在编写一个简单的 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();
}
最佳答案
As @grzenio said ,看来您的问题与以下事实有关:您正在对在不同线程上创建的 Windows 窗体控件进行跨线程调用。
如果您使用的是 .NET 4.5 (C# 5.0),我建议您查看 async/await keywords ,很好的介绍可以在Stephen Cleary's Blog找到
关于如何使用遗留“DoStuff”进行异步和等待的示例:
private async void _Timer_Tick(object sender, EventArgs e)
{
_Timer.Enabled = false;
await Task.Run((() => DoStuff()));
_Timer.Enabled = true;
}
注意事项:
- 异步已添加到 Timer_Tick 事件的签名中。
- await 关键字和 Task.Run 用于异步运行 DoStuff。
当使用这些关键字时,DoStuff 将异步运行,一旦 DoStuff 返回,它将使用最初调用 Tick 的线程的上下文在 await 之后继续在线。
关于c# - 计时器在禁用后不想再次启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21551856/