C# Open Form in a new Thread or Task?

Viewed 7782

How do i open a new form in C#, with the thread or task.

example:

public void openform()
{
    Form _form = new Form();
    _form.show()
}

Thread _thread = new Thread(openform);
_thread.start();

if i use a Thread it opens the form and close it again.

3 Answers

You can create another UI thread if you simply set the ApartmentState to STA and start another message loop:

Thread _thread = new Thread(() =>
{
    Application.Run(new Form());
});
_thread.SetApartmentState(ApartmentState.STA);
_thread.Start();

Note that you wont't be able to display a control that you create on the main thread on this form though. That's why it is generally a bad idea to create more than one UI thread.

Thread thd = new Thread(() =>
            {

                //Do Some stuff 
                //Do some more stuff

                var dispatcher = Dispatcher.CurrentDispatcher;
                dispatcher.UnhandledException += Dispatcher_UnhandledException; //you exception handling logic
                Dispatcher.Run();
            });
            thd.IsBackground = true;
            thd.SetApartmentState(ApartmentState.STA);
            thd.Start();

based on your use case call Dispacther.InvokeShutdown(); when done.

By using ShowDialog it return only when the window is closed:

new Thread(() => new MyForm().ShowDialog()).Start();
Related