The calling thread must be STA, because many UI components require this


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.

Dispatcher.CurrentDispatcher.BeginInvoke((Action) (() =>
 

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.

private readonly Dispatcher dispatcher;
 
public DemoViewModel()
{
this.dispatcher = Dispatcher.CurrentDispatcher;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s