Mike O
Mike O

Reputation: 291

How to achieve thread safety with a timed Windows Forms update?

In my C# program I'm trying to get a Panel to call OnPaint() once a second to do some Graphics drawing based on current settings. The main form uses a System.Timers.Timer to call the Panel class' update method, which ends with a Refresh() call. But when I run it, I always get an InvalidOperationExcetpion that refers to the Refresh line and says "Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on." It also refers me to this MSDN page: http://msdn.microsoft.com/en-us/library/ms171728.aspx

But all the examples on that page seem to suggest tying a new thread to a specific form event. I'm updating based on a timer, not a mouse click or similar event. Running the refresh on a separate thread sounds good to me, but I'm not sure how I'd do it (I'm good with Java, but a C# newbie).

Upvotes: 1

Views: 1270

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502845

The main form uses a System.Timers.Timer to call the Panel class' update method

Two options:

Basically, you shouldn't access UI elements from a different thread - you can marshal to the right thread via Control.Invoke or Control.BeginInvoke, but if you don't have any significant work to do other than updating the UI, you might as well just force the timer to raise the event in the UI thread.

Upvotes: 8

Related Questions