Search code examples
.nettimertask-parallel-library

Timer not enabled again after Task.ContinueWith


I have a job timer, which checks every minute if there is something to do. If there is something to do, the timer stops, the task begins (startTimer) which mostly needs a few minutes, and after the task the timer should start again...

But it didn't work...

    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;
    }

This works but the Timer will tick again after one minute and this is not good, because the last tick isn't even finished...

    private void JobTimer_Tick(object sender, EventArgs e)
    {
        WriteLog("-------------------------------------------");
        WriteLog("-----------------Jobtimer Tick-------------");
        WriteLog("-------------------------------------------");
        JobTimer.Enabled = false;
        Task.Factory.StartNew(() => StartWorker());;
       JobTimer.Enabled = true;
    }

Solution

  • System.Windows.Forms.Timer runs on the UI thread so you need to synchronize your continuation task with the UI thread

    Task.Factory.StartNew(() => StartWorker()).ContinueWith((a) => JobTimer_AfterTick(JobTimer), TaskScheduler.FromCurrentSynchronizationContext());