Link to home
Create AccountLog in
Avatar of deleyd
deleydFlag 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.)
Avatar of Eduard Ghergu
Eduard Ghergu
Flag of Romania image

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

ASKER

Can it also be done from a created thread with STA explicitly set?
ASKER CERTIFIED SOLUTION
Avatar of Eduard Ghergu
Eduard Ghergu
Flag of Romania image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account