When is invoke required on GUI objects?

2019-02-25 10:54发布

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?

3条回答
Luminary・发光体
2楼-- · 2019-02-25 11:14

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.

查看更多
我只想做你的唯一
3楼-- · 2019-02-25 11:17

This should tell you Control.InvokeRequired

查看更多
老娘就宠你
4楼-- · 2019-02-25 11:30

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.

查看更多
登录 后发表回答