Two UI threads in c # windows

How can I implement two ui threads in a C # Windows application?

+4
source share
3 answers

You need to call Thread.SetApartmentState () to switch the thread to STA before starting it. And start the message loop so that all windows created on this thread are alive, Application.Run (). Application.ExitThread () will end the message loop and cause the thread to exit. Using Run (Form) does this automatically, as in the main thread.

Beware, however, that it may be difficult for the user to handle the windows that you create in this stream. They have no Z-order relationship with windows in the main thread; the desktop is their parent. This leads to the fact that they are easily lost behind another window, including your own. Adverse workarounds for this are TopMost and pinvoking SetParent ().

+7
source

This may not be the answer, but more explanation.

If two threads were allowed to access the same pixel at the same time - something that would be due to the presence of a multi-threaded user interface - you will need some kind of synchronization between the threads. If the threads are not synchronized, how to determine the color of the pixel?

Thus, we will need to add a lock. Pixel locking is very expensive, so we will soon move on to locking for each control or for each window. There you go: allowing 1 and only 1 thread to access the user interface, we implemented a lock.

BTW: replace the pixel with control or controltree; it's not just about pixels about shared data, be it a pixel or a control.

+5
source

Call Application.Run(...) in a new thread and open the form using its own message loop.

 new Thread(() => Application.Run(someForm)).Start(); 
+1
source

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


All Articles