There is a timer code that must be run in a separate thread when the mouse is clicked.

private void button1_Click(object sender, EventArgs e) { Thread tmr = new Thread(TimerStart); tmr.Start(); } private void TimerStart() { date = DateTime.Now; timer1.Interval = 10; timer1.Tick += new EventHandler(TicTimer); timer1.Start(); } private void TicTimer(object sender, EventArgs e) { long tic = DateTime.Now.Ticks - date.Ticks; DateTime stopwath = new DateTime(); stopwath = stopwath.AddTicks(tic); label1.Text = string.Format("{0:HH:mm:ss:ff}", stopwath); } 

However, nothing happens. If I just call the method:

  private void button1_Click(object sender, EventArgs e) { TimerStart(); } 

works without question. What is the problem?

  • I can be mistaken, but it seems to me that it starts up, but label1.Text = string.Format ("{0: HH: mm: ss: ff}", stopwath); This is an error that gives an error, go through the invocation. You need to update the same label, google it - Rostyslav Kuzmovych
  • Judging by the signature, it is System.Windows.Forms.Timer . His event is launched in a guay stream. I think you need a timer whose event runs in a separate thread. Take the System.Threading.Timer . But do not run it yourself in a separate thread! And yes, you will need to use Invoke to access the controls. - Alexander Petrov
  • Is @AlexanderPetrov a typo? - Sergey
  • This is from the English abbreviation GUI - the graphical user interface - the graphical user interface. In our opinion, there will be a "goo" - everyone says so :). - Alexander Petrov
  • @AlexanderPetrov about Invoke did not understand. It is necessary to add to this line - label1.Text = string.Format("{0:HH:mm:ss:ff}", stopwath); - Sergey

2 answers 2

I would advise you to use the System.Timers.Timer timer and use its Timer.Elapsed event. The advantages of this approach are obvious: the method subscribed to this event runs in a free stream from the thread pool ThreadPool , so your main UI thread is not blocked for the duration of the time-consuming operation. If the method subscribed to the Elapsed event has to change something on the form, then you can use Invoke and MethodInvoker to MethodInvoker through the context of synchronization of the necessary information into the form's UI stream.

  private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { timer.Stop(); Invoke(new MethodInvoker(MethodForInvoke)); timer.Interval = 5000; timer.Start(); } 

The method of starting such a timer in a separate thread looks like this:

  public void Run() { timer.Interval = 5000; timer.Start(); while (!stopFlag) { Thread.Sleep(1000); } timer.Stop(); } 

If you want to stop the stream with a timer, just send stopFlag=true , where stopFlag is the field of the class in which the Run() method is located.

    Simple BeginInvoke(new Action(() => timerStart.Enabled = true)); method BeginInvoke(new Action(() => timerStart.Enabled = true));