Avatar of deleyd
deleyd
Flag for United States of America asked on

C# WPF STA thread

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#

Avatar of undefined
Last Comment
Eduard Ghergu

8/22/2022 - Mon
Eduard Ghergu

Hi,

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),
deleyd

ASKER
Can it also be done from a created thread with STA explicitly set?
ASKER CERTIFIED SOLUTION
Eduard Ghergu

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck