Accessing controls from another thread inside a class

herculesvba

New member
Joined
Jan 26, 2015
Messages
2
hi guys,

i use a second thread to calculate a value for a textbox placed on the main form.
I use delegate and invoke, which works well as long as i let the complete code in the form code class.

If i generate a new class, and move the code to this class, i get an error that the control handle doesn't exist yet, after starting the second thread.

The textbox is visible and not modified in any way.

What's the difference between starting a thread from a form class or fron a separate class?


Any idea what can causing this issue.?

Any help would be appreciated


Regards Thomas
 
Last edited:
There is no difference. The exact same code will work no matter where it is. Your problem is almost certainly that you're not actually using the control on the form that you want to affect in order to perform the delegation but some other control that you create in that class. Ideally, if you want to affect the UI from a class that is not itself a UI element then you should use the SynchronizationContext class. See post #17 in the following thread for an example:

Accessing Controls from Worker Threads

That example does use code from a form but the same thing will work in a non-UI element too. The principle is that you get the value of SynchronizationContext.Current on the UI thread and then that object can be used anywhere to invoke a method on that UI thread. You would generally create the object containing the code on the UI thread and get the current SynchronizationContext as part of the initialisation of the object.
 
Back
Top