I know I can start a new worker thread from with .NET. But how do I start a new UI thread (like in MFC)?
I don\'t mind if the solution is restricted to Windows boxes
If you're looking to create a new thread that is capable of creating and dealing with Window handles, then you can use the SetApartmentState
function on the Thread object and set it to STA
. You'll also likely need to call Application.Run
inside the method for this thread in order to create your message loop. However, bear in mind that you're subject to the same cross-threading no-no's that you have in any other thread (ie, you can only interact with the handle for a control on the thread inside which it was created), so you can't do anything on your other UI thread without switching contexts.
If you are interested in using WPF, check out MSDN's article WPF's Threading Model, in particular the "Multiple Windows, Multiple Threads" section. It details what you need to do to create a new Dispatcher and show a window on a new thread.
Also you can do this:
delegate void MyProcHandler(object param1, object param2);
MyForm.Invoke
(
new MyProcHandler(delegate(object param1, object param2)
{
// some code
}),
null,
null
);
Use Application.Run - it starts a message loop in the current thread. There are overloads to take a form to start with, or an application context, or neither. (If you want to do this for a new thread, you need to create the thread and start it in the normal way, and make it call Application.Run
.)