Whilst working on my current WPF application, I was at Sixes & Sevens trying to correct the following error;
Message: The calling thread must be STA, because many UI components require this
I ended up hacking my way out of this problem a week or so ago, hacks however, make me feel extremely dirty, and subscribing to the “leave code as you would like to find it” mantra meant one had to subsequently revisit it to “tidy-up”. I have a strictly MVVM application that is complex and multithreaded, needing to update UI components from web service calls that typically are asynchronous. The issue here was that I was using code like this in my view model thinking I had access to the dispatcher.
The mistake I made was in not getting a reference to the correct dispatcher.
To correct this issue, ensure you have a variable that gets a reference to the correct dispatcher when the view model is instantiated, you can then use this dispatcher in your view model, without having to pollute your code behind files.