How to open a window in a separate stream?

I would like to:

Window newWindow = new Window(); newWindow.Show(); while (true) { Console.Write("spin"); } 

Ie I do an intensive calculation in the main window, but this new window (where I try to show the busy indicator with animation) does not respond (it is frozen) ...

So, I tried:

 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. Does anyone know what's wrong here?

+4
source share
4 answers

You should not open a new window in your stream.

Instead, push the computational work you do onto the background thread and leave the user interface thread free. The easiest option for this is to use BackgroundWorker . It automatically handles marshaling progress and completion for the user interface stream.

However, you can do it yourself using threads or Task / Task<T> . Remember to use the dispatcher or TaskScheduler, created from the context of the user interface, for anything that will update the user interface, such as tracking progress.

+8
source

You don’t have - only one GUI thread. If you need to do blocking work, this stuff should go in the background thread.

+2
source

You need to start a separate message loop in a new thread using the Application class.

+2
source

@SLaks This can be very useful if you are trying to launch a new window from a console application. One option is to use showDialog(); But then it’s hard to close it.

If you use Show() , then Application.run() (these are nuts and bolts using the Application class to start a new message loop)

When you call Application.Exit() in your main console thread, the application actually closes;

using showDialog() , you must interrupt the stream, and then wait until the window receives some input, i.e. mouse or focus. otherwise it will go out forever.

+1
source

Source: https://habr.com/ru/post/1346954/


All Articles