We help IT Professionals succeed at work.

C# WPF STA thread

deleyd
deleyd asked
on
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.)
Comment
Watch Question

Eduard GherguArchitect - Coder - Mentor

Commented:
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),
deleydSoftware Engineer

Author

Commented:
Can it also be done from a created thread with STA explicitly set?
Architect - Coder - Mentor
Commented:
Hi,
Purely from WPF perspective, STA is not relevant. Maybe is something in the background thread that’s using a COM component under the hood.