Hi,

I am using a System.Threading.Timer and I'm trying to update a form's UI each time the timer fires. When I push a button I start the timer, execute some task that takes a while to complete and then stop the timer.

I have the following code:
Code:
DateTime dtStart;
private System.Threading.Timer tmr;

private void Form1_Load(object sender, EventArgs e)
{
     tmr = new System.Threading.Timer(new TimerCallback(timer_Elapsed), null, System.Threading.Timeout.Infinite, 1000);
}

private void btnWebSync2_Click(object sender, EventArgs e)
{
      dtStart = DateTime.Now;
      tmr.Change(0, 1000);                                             // start the timer
      Thread.Sleep(5000);                                              // some long running task
      tmr.Change(System.Threading.Timeout.Infinite, 1000); // stop the timer
}

void timer_Elapsed(object state)
{
      TimeSpan ts = DateTime.Now.Subtract(dtStart);
      string elapsedTime = string.Format("{0:00}:{1:00}:{2:00}.{3:000}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);
      Debug.Print(elapsedTime);

      this.Invoke((MethodInvoker)delegate()
      {
           label1.Text = "Elapsed time - " + elapsedTime;
      });
}
I have calls to Debug.Print in the timer callback and I can see that the timer is actually firing but my UI is only updated when the timer is stopped. Any ideas what I'm doing wrong?

Thanks,

dlarkin77