Can I use a timer to update a label every x milliseconds

user1678541 picture user1678541 · Sep 13, 2012 · Viewed 18k times · Source

This is my code:

Stopwatch timer = new Stopwatch();
timer.Start();
while (timer.ElapsedMilliseconds < 3000) {
    label1.Text = Convert.ToString( timer.ElapsedMilliseconds );
}
timer.Stop();

My intetion was to update the label's text in real time, so if timer.ElapsedMilliseconds == 1350, then label1.Text = 1350. How can I do this? Thanks in advance!

Answer

Tigran picture Tigran · Sep 13, 2012

You better to use System.Windows.Forms.Timer for this, and not Stopwatch()

Even if that timer is less accurate then StopWatch(..) it gives you a good control.

Just example sniplet:

   myTimer.Tick += new EventHandler(TimerEventProcessor);       
   myTimer.Interval = 1350;
   myTimer.Start();

   private void TimerEventProcessor(...){          
     label1.Text = "...";
   }