Filip Frącz
Filip Frącz

Reputation: 5947

How to start a UI thread in C#

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 only; I also would like the solution to be purely .NET - no p/invokes to CreateThread, etc.

Any input appreciated.

Upvotes: 8

Views: 18140

Answers (4)

Erich Mirabal
Erich Mirabal

Reputation: 10048

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.

Upvotes: 4

galets
galets

Reputation: 18502

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
    ); 

Upvotes: 0

Adam Robinson
Adam Robinson

Reputation: 185693

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.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503290

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.)

Upvotes: 24

Related Questions