Thread Form

P

PCH

I have a main form that loads and stays open.

I have 3 other forms that I want to open, which each do various displays /
tasks. Each has 1+ timers on them as well.

I'm worried that the timers will overlap and will execute code at the same
time.. degrading each other performance.

I was thinking about loading each of those forms into its own thread,
instead of just calling new/show from the main program thread.

The problem I have is when i create a new thread and open the form in it..
it opens.. but once the threadstart finished.. the thread closes itself! So
the form closes! I saw some examples where you can do a loop and sleep that
thread until you want to close it, and that solves the automatic closing
problem, but then the form it has loaded never does anything because its
forced to sleep over and over!

So.

How can I load a form into a new thread, keep that thread open, and have the
form go on its merry way without impacting performance?

Thanks
 
A

Alex Feinman [MVP]

It is better to keep all the forms in the same thread (although not
necessary). Form created via a separate thread will require implementing a
message loop in that thread, which is not a trivial excersise.
Timers implemented via timer control execute via windows message. Each
message is processed in the context of the GUI thread of which there is
usually one. This means that the timer will not preempt another timer as
long as you don't call Application.DoEvents inside the timer event handler.
Note that this does not apply to the System.Threading.Timer which is a horse
of entirely different hue.

Why would you want to invoke Application.DoEvents? To redraw changed UI
elements. E.g. if you are calling Control.Text = "some new text", it will
not actually be displayed unless you call Application.DoEvents or
Control.Update.

I suggest you rethink your design considering the above - most likely you
don't need to create a form on a separate thread at all.
 
C

Chris Tacke, eMVP

I guess the #1 question is why do you think htey need to be on separate
threads? It's possible, but not trivial, as you'll have to create a message
pump on each thread and communication between Forms gets a lot more complex.

-Chris
 
P

PCH

Well I was worried that 1 timer event may take a long time to execute and
that would force the other timer events to wait until its completed....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top