3

Using C# Windows.Forms, do the methods Invalidate(), Refresh(), etc. have to be run on the main/GUI thread (require Invoke/BeginInvoke)? How about changes to members of a GUI object such as adding/deleting Points or changing the Color of a Series in a Charting.Chart object?

I have some of these changes occuring in a worker thread without any issues (so I guess they are ok?), but I'm trying to distinguish which changes are explicity required on the GUI thread and which changes can occur on the object in a worker thread. Does anyone have a link or book reference to guidance on this subject?

Jess
  • 2,991
  • 3
  • 27
  • 40
  • Anything that uses a window handle – David Heffernan Apr 05 '11 at 16:16
  • 2
    Classes can be thread-unsafe without them telling you so explicitly with an exception. The List<> class would be an example. Only ever use members of a class whose instance was created or members accessed on another thread when the docs tell you that the member is thread-safe. It is quite rare, the Chart class certainly isn't. This is not something you 'risk', the cost of guessing wrong is huge. – Hans Passant Apr 05 '11 at 16:54

3 Answers3

4

In general, you should typically assume that ALL changes to GUI elements should be made on the UI thread.

Often, changes on a background thread will work during testing, but break post-deployment. In general, unless otherwise documented, it's much safer to assume that everything should be on the UI thread.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
1

You can not make synchronous method calls that manipulate WinForms controls on a worker thread.

I'm not sure what "adding/deleting Points" is referring to, or the Charting.Chart class. This class may encapsulate GUI Thread invocation on their own.

Generally speaking, if you are modifying the size, text, background color, or other properties on a Control, this must use Invoke / BeginInvoke.

Stealth Rabbi
  • 10,156
  • 22
  • 100
  • 176
-1

This should tell you Control.InvokeRequired

František Žiačik
  • 7,511
  • 1
  • 34
  • 59