Problem with mulitthreading a winform app

A

Alex

My app consists of the main application form, which spawns a thread that
exists for the life of the application. This thread will need to launch
other forms based on some logic at periods of time, but when I do it
directly from this thread, the application hangs. So I had the thread spawn
another dedicated thread that would show the other form. The application
still hangs. What am I not thinking about?
 
W

Wiktor Zychla

My app consists of the main application form, which spawns a thread that
exists for the life of the application. This thread will need to launch
other forms based on some logic at periods of time, but when I do it
directly from this thread, the application hangs. So I had the thread spawn
another dedicated thread that would show the other form. The application
still hangs. What am I not thinking about?

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnforms/htm
l/winforms06112002.asp
 
H

Herfried K. Wagner [MVP]

Hello,

Alex said:
My app consists of the main application form, which
spawns a thread that exists for the life of the application.
This thread will need to launch other forms based on some
logic at periods of time, but when I do it directly from
this thread, the application hangs. So I had the thread spawn
another dedicated thread that would show the other form.

http://www.devx.com/dotnet/Article/11358
 
1

100

Hi Alex,
The problem is that the message queues and loops are per thread. In other
words when you create the second form in the worker thread there is no
message loop to pump messages out to the form and it stays freezed.

In order to have this second form alive you have to start a message loop in
the worker thread.
you can do that like this:

<<in the main thread>>
Thread t = new Thread( new ThreadStart(SecFormThreadProc));
t.Start();

<<in the worker thread>>
private static void SecFormThreadProc()
{
SecondForm sf = new SecondForm();
//The following line starts normal message loop in the current thread.
// The thread ends when the form gets closed
Application.Run(sf);
}

Be careful. The new thread is no more like *worker* thread. It is rather an
UI thread. You cannot spin gears in loops inside the thread because this
will make your form to hang again. The process inside this thread has to be
event driven.
If you want to update controls on this second form from the main thread you
have to use Control.Invoke.

HTH
B\rgds
100
 

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