我有一个工作计时器,它每分钟检查是否有事情要做。如果有事情要做,计时器停止,任务开始(startTimer),这通常需要几分钟,任务结束后计时器应该再次启动...
但是没用...
private void JobTimer_Tick(object sender, EventArgs e)
{
WriteLog("-------------------------------------------");
WriteLog("-----------------Jobtimer Tick-------------");
WriteLog("-------------------------------------------");
JobTimer.Enabled = false;
Task.Factory.StartNew(() => StartWorker()).ContinueWith((a) => JobTimer_AfterTick(JobTimer));
}
private void JobTimer_AfterTick(System.Windows.Forms.Timer t)
{
t.Enabled = true;
}
这可行,但计时器会在一分钟后再次滴答,这不好,因为最后一次滴答甚至还没有完成......
private void JobTimer_Tick(object sender, EventArgs e)
{
WriteLog("-------------------------------------------");
WriteLog("-----------------Jobtimer Tick-------------");
WriteLog("-------------------------------------------");
JobTimer.Enabled = false;
Task.Factory.StartNew(() => StartWorker());;
JobTimer.Enabled = true;
}
System.Windows.Forms.Timer 在 UI 线程上运行,因此您需要将延续任务与 UI 线程同步
Task.Factory.StartNew(() => StartWorker()).ContinueWith((a) => JobTimer_AfterTick(JobTimer), TaskScheduler.FromCurrentSynchronizationContext());