views:

107

answers:

3

When I'm creating a simple Windows form, is it starting in a new thread automatically? Or there is only one thread for all forms?

A: 

No, It's only a message queue. forms (windows) looks like they are "multithreading" but this is message queue / message pump that processes messages. (so it's 1 thread...)

Dani
+3  A: 

There is one thread for all forms.

In fact, Windows Forms (and most windowing technologies), require that all of your forms and controls be generated on a single thread. If you try to use a control from a different thread, it will cause a problem.

The UI thread in a Windows application actually spends most of its time idle. There is a message queue that is processed, and which causes the events you handle to be raised. If you want to access the UI from another thread, you have to invoke (using Control.Invoke) the method you want to run back onto the UI's thread, or you will receive exceptions.

Reed Copsey
What will this code do? new Thread(new ThreadStart(delegate() { Form f = new Form(); f.Show(); })).Start();
Philip Wallace
As I commented in another post - you CAN do this. However, your code, as above, will cause a huge amount of instability, and probably crash. If you want to do this, you should do Application.Run(new Form1()) inside of the thread, AND make sure the thread is set to Single threaded apartment state prior to calling Start. If you do that, you can start a new message pump on a secondary thread, and run this. It's just not the "normal" way of working, or good practice.
Reed Copsey
+1  A: 

If you do not do anything extra, all forms share the same UI thread (i suppose this is what you are referring to)

anchandra
However, if you are using wpf, you can have separate ui thread for each form. See this article for more details: http://eprystupa.wordpress.com/2008/07/28/running-wpf-application-with-multiple-ui-threads/
anchandra
It's technically possible to do this in Windows Forms, too - just have multiple Application.Run calls in STA threads - but it's usually not necessary or a good idea, IMO.
Reed Copsey