views:

31

answers:

2

I understand that multi-threaded WinForms apps are required to use Control.Invoke or Control.BeginInvoke when accessing a control from a thread other than the UI thread.

But does this rule also apply when manipulating objects that are contained within a control but which do not derive from the Control base class?

For example, when using a WebBrowser control, is it OK to manipulate the DOM without using Control.Invoke?

Thanks, Tim

A: 

This applies to everything inheriting from Control.

By the way: you can just try this. It normally automatically throws under debug mode when you're accessing the methods illegally.

Pieter
Thanks - my own tests suggested this to be the case but the MSDN documentation suggests that threading problems are intermittent, so I was cautious.
Tim Coulter
Under release, it doesn't throw. That's the reason it's described as intermittent. The reason you need to invoke is that when methods interact with the real Windows (HWND) objects, you must be on the same thread. However, not all methods of a control do this. Better to be safe.
Pieter
A: 

The answer is most definitely no. The reason is because you really have no idea when and how the Control will use the contained object and you certainly cannot inject the necessary synchronization mechanisms inside the Control. For example, what would happen if the Control needs to access the object from the WM_PAINT message at the same time you are manipulating it from a worker thread? You could put the necessary locks on your side, but there is pretty much nothing you could do to get the internal plumbing of the Control to do the same.

Brian Gideon
Thanks for the clarification Brian. So, if I understand correctly, although my code appears to run correctly (even in debug, as per Pieter's comment) I still need to wrap Control.Invoke() around every call to a method on a contained class instance? Is this true even if the control (e.g. WebBrowser) and the contained classes (e.g. DOM objects) are just wrappers around objects exposed by COM interop?
Tim Coulter