I want to create multiple UI threads in my application. I have simulated the scenario as below. I am creating a new window / form on a button click in a background
You could handle the MainForm.Closing event and call subForm.Close ( marshalled onto the right thread ) for each sub form.
I'm not sure why you want the forms on separate threads, though. Can't you just display the sub forms non-modally on the main thread?
I think you will need to set the apartment state of your thread to single threaded as indicated here ApartmentState for dummies and here Thread-safe Form.Show: t.SetApartmentState(ApartmentState.STA)
. I don't know if that's possible on a background thread though.
Another thing that I would urge you to look at is MDI (multiple document interface, e.g. here). Do you really need different forms display as an own window or are they rather documents inside a common form? You may have of course a reason to create multiple UI threads.
Messing with threads will only bite you sooner or later.
From MSDN:
Controls in Windows Forms are bound to a specific thread and are not thread safe. Therefore, if you are calling a control's method from a different thread, you must use one of the control's invoke methods to marshal the call to the proper thread
You can of course use as many threads as you like, but don't try to create a workaround to be able to use different threads for updating the UI. Use Invoke
/InvokeRequired
from your worker/background threads instead.
Using an extension method makes it cleaner: Automating the InvokeRequired code pattern