开发者

Control.invoke and parent control

Lets say I have a form called MainForm and a control on it: somelabel. In order to access these controls from another thread I have to use I开发者_Python百科nvoke method. e.g:

somelabel.Invoke(...);

However I can also access the label through the form like this:

MainForm.Invoke(...) //Code for manipulating somelabel

Is there any difference between these two snippets in terms of performance or some other technical aspect?


No. Every Windows forms control exposes an Invoke method, and they all function the same way. No matter which control you use (whether the form or a child control), you'll still doing the same basic operation, so performance will be the same.

I, personally, prefer to use the form instead of individual controls. This makes it easier to rework the design later, as you can remove or add controls without breaking your code that invokes through the form. Another good option is to use the WindowsFormsSynchronizationContext, which you can retrieve via SynchronizationContext.Current. This gives you a way to generate a synchronization context you can use (via Send/Post instead of Invoke) that does the same thing, but is not tied to any control.


Not really... the important thing is that both of these controls are using the same UI thread. Really you're only using the control to work out which thread to marshal the delegate call onto. It's generally clearer to use whichever control you're about to actually use, but the result will be the same.

Note that it does make a difference if you've got two different windows using two different UI threads (e.g. a splash screen which is displayed using one UI thread while the other is busy building the main UI). There are only a few situations where you'd want multiple UI threads, but the golden rule is that all the controls within one window must use the same UI thread, so using any UI object within the same window should be fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜