locked
step into problem while using timer callback function RRS feed

  • Question

  • Hello

    Im using System.Timers.Timer in my Windows forms application.
    My OnTimedEvent function looks like this:

    ...
    label1.Text = "Player 1:   " + time1.ToLongTimeString();
    ...

    when i start debugging application, everything works ok, but when i want to step into with F11 or step over with F10 i always get this message:

    System.InvalidOperationException was unhandled by user code
      Message="Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on."
      Source="System.Windows.Forms"
      StackTrace:
           at System.Windows.Forms.Control.get_Handle()
           at System.Windows.Forms.Control.set_WindowText(String value)
           at System.Windows.Forms.Control.set_Text(String value)
           at System.Windows.Forms.Label.set_Text(String value)
           at chess.Form1.OnTimedEvent(Object source, ElapsedEventArgs e) in C:\Documents and Settings\lazar\My Documents\Visual Studio 2008\Projects\chess_net_together_1_modified\chess\Form1.cs:line 560
           at System.Timers.Timer.MyTimerCallback(Object state)
      InnerException:

    Why is this happening only when im trying to step the program. Should I change the code and change the label1.Text on another thread just for purposes of stepping? Thanks for any advise. --Martin
    Friday, April 17, 2009 2:51 PM

Answers

  • RudeDog has a great suggestion.  Also, if you need a repeated event on a Windows Form, use the System.Windows.Forms.Timer class instead of the System.Timers.Timer class. The Tick event of the System.Windows.Forms.Timer class runs on the UI thread, so you won't get this error.
    David Morton - http://blog.davemorton.net/
    • Marked as answer by nobugz Friday, April 17, 2009 7:16 PM
    Friday, April 17, 2009 5:40 PM

All replies

  • Generally speaking, you cannot or should not try to directly access objects in one thread from another thread.  Pass data back forth with events and callbacks.  The BackgroundWorker is already set up to do this.
    Mark the best replies as answers. "Fooling computers since 1971."
    Friday, April 17, 2009 5:38 PM
  • RudeDog has a great suggestion.  Also, if you need a repeated event on a Windows Form, use the System.Windows.Forms.Timer class instead of the System.Timers.Timer class. The Tick event of the System.Windows.Forms.Timer class runs on the UI thread, so you won't get this error.
    David Morton - http://blog.davemorton.net/
    • Marked as answer by nobugz Friday, April 17, 2009 7:16 PM
    Friday, April 17, 2009 5:40 PM