Is running a Control in a separate thread allowed?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a form, and from the form when a user clicks a button, it instantiates
control that will be doing a lot of logic. I am trying to use
System.Threading.ThreadPool.QueueUserWorkItem to spawn a background thread
off the pool. I stepped through the logic, and everything seems to go
through fine when the control is initialized, and my main form continues to
work correctly. The only issue is that the control seems to not render
properly and freeze (even after its contructor has been called and completed).

Any ideas or suggestions on how to run a control in a different thread than
the main windows form?
 
Hi,

RWF said:
I have a form, and from the form when a user clicks a button, it
instantiates
control that will be doing a lot of logic.

A control? You better put your logic in a separate class.
I am trying to use
System.Threading.ThreadPool.QueueUserWorkItem to spawn a background thread
off the pool. I stepped through the logic, and everything seems to go
through fine when the control is initialized, and my main form continues
to
work correctly. The only issue is that the control seems to not render
properly and freeze (even after its contructor has been called and
completed).

You cannot do that, all the UI interactions have to be done from the UI
thread.
What you can do is do your processing in a worker thread and using
Control.Invoke to send messages back to the UI thread.
 
RWF,

You should not run a control in a separate thread, especially if it is
parented in a window that was created on another thread.

What you want to do is not actually try and retrieve values from your
control or set them in another thread. Store the values in variables, then
access those from another thread. When you want to update the control, you
will need to make a call to the Invoke method on the control, passing a
delegate which will set the values on your control for you. The Invoke
method will guarantee that the fields get updated correctly.

Hope this helps.
 
I tried using BeginInvoke, but that seemed to still lockup my main form from
receiving an update, or even being moved around the screen.
 
Can you post up a simple example? btw note I am saying to not start your
other control in another thread .. I am saying to have a background threadin
your other control that then calls Control.BeginInvoke to have the main
thread update the control.

Cheers,

Greg Young
MVP - C#
http://geekswithblogs.net/gyoung
 
Back
Top