I make a stopwatch that should work in a separate thread from the GUI, but output time in the label . The stopwatch should work in parallel with the rest of the GUI operations:

  DateTime date; private void button1_Click(object sender, EventArgs e) //запуск таймера { System.Timers.Timer timer = new System.Timers.Timer(10); timer.Elapsed += timer_Elapsed; timer.Start(); } void timer_Elapsed(object sender, ElapsedEventArgs e) { date = DateTime.Now; 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); } 

The error is СrossThreadMessagingException . How to fix it?

    2 answers 2

      this.Invoke(new Action(() => { label1.Text = string.Format("{0:HH:mm:ss:ff}", stopwath); })); 
    • I would have also formatted it above by code, so that only assignment is performed in the gooey thread. - Alexander Petrov
    • Nothing changes - Sergey
    • What do you want to output? tic will always be 0, because you have tic = DateTime.Now.Ticks - date.Ticks and date = DateTime.Now that is, tic you have the difference between the same values. stopwath will always be 0. - koshe

    You cannot access the GUI from another thread.

    The GUI is bound to the thread in which it was created.

    You need to use Invoke or async/await

    • can you give an example - Sergey