I encountered some C# WPF code (written by other people) and I think the problem they were trying to solve was displaying a message window from a background thread, and getting the error "The calling thread must be STA, because many UI components require this."
So it looks like they decided to fix this by creating their background thread and setting the ApartmentState to STA before running it.
I'm skeptical if this is a valid solution.
I'd like to know if I can prove this can lead to problems, or is there some official documentation somewhere that says "Don't do this."
(Because I eventually need to make a decent argument that will be convincing to others.)
(I'm used to instead using Dispatch to run code on the UI thread.)
(I do admit there is a need to somehow deal with "the background thread encountered a problem and we need to tell someone about it". I suspect setting the background thread to STA is not the proper solution.)
.NET ProgrammingC#
Last Comment
Eduard Ghergu
8/22/2022 - Mon
Eduard Ghergu
Hi,
You can use Dispatcher.Invoke to update your GUI from a secondary thread.
The update of the UIThread from the background thread can lead to deadlocks or unwanted data values if components are not thread-safe (check documentation),
deleyd
ASKER
Can it also be done from a created thread with STA explicitly set?
You can use Dispatcher.Invoke to update your GUI from a secondary thread.
https://stackoverflow.com/questions/4253088/updating-gui-wpf-using-a-different-thread
The update of the UIThread from the background thread can lead to deadlocks or unwanted data values if components are not thread-safe (check documentation),