问题
I have a library that needs to call the main windows thread in UWP when it receives a message from a communication channel (let say, a message indicating a check box should be checked). The library saves a copy of the SynchronizationContext when it starts up, so it can Post back to it when the data comes in, but the trouble is, I'm not guaranteed that the caller of this library is on the main thread when it's initialized.
Is there some simple, guaranteed way to obtain the Main Window Thread (that is, the Windows' SynchronizationContext) so I don't need to rely on the caller to make sure the contexts aren't switch?
回答1:
Trying to push something onto "the main window thread" will fail eventually when you pick the wrong window / thread. A better design is to have the library expose an event and then any consumer (including the main window) can listen to that event and do the appropriate thread marshalling (if any) for itself.
If you absolutely must get "the main window" then CoreApplication.MainView.CoreWindow
will do it.
来源:https://stackoverflow.com/questions/51602879/how-do-you-find-the-main-window-thread-in-uwp