Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a window in a separate thread?

Tags:

c#

wpf

I'd like to do:

Window newWindow = new Window();
newWindow.Show();

while (true) 
{
    Console.Write("spin");
}

I.e., I'm doing an intensive calculation in main window, but this new window (where I'm trying to show a busy indicator with an animation) is not responding (it's frozen)...

So I tried to do:

Thread thread = new Thread(() =>
{
    Window newWindow = new Window();
    newWindow.Show();
});

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

while (true) 
{
    Console.Write("spin");
}

But the new window is still frozen, etc. Anyone know what's wrong here?

like image 574
Shai UI Avatar asked Dec 12 '22 14:12

Shai UI


1 Answers

You shouldn't try to open a new Window in it's own thread.

Instead, push the computational work you're doing into a background thread, and leave the UI thread free. The simplest option for this is typically to use BackgroundWorker. It handles the marshaling of progress and completion back to the UI thread for you automatically.

However, you can do this yourself using threads or Task/Task<T>, as well. Just remember to use the Dispatcher or a TaskScheduler created from the UI context for anything that will update the UI, such as progress notifcication.

like image 69
Reed Copsey Avatar answered Dec 30 '22 08:12

Reed Copsey