Running MTA code in an STA thread

I don’t claim to understand the windows threading model that well.  For that matter, I don’t want to learn either.  But every so often you hit an error like this:  “WaitAll for multiple handles on a STA thread is not supported.”.  Now, we’ll calmly step away from the car crash that is understanding the apartment threading model and skip straight to making the problem go away.

private void RunInMtaThread(ThreadStart action)
{
    var thread = new Thread(action);
    thread.SetApartmentState(ApartmentState.MTA);
    thread.Start();
    thread.Join();
}

Incidentally, the SetApartmentState call isn’t actually necessary, since it’s the default.  I’m including it so that it’s obvious how to achieve the reverse.  As an aside, I’ve been spending a lot of time thinking about API design (Ayende’s opinionated API article started me on this road), and I can think of no good reason that the apartment state should not be an optional parameter of thread start, rather than a settable property.  It’s not like you can change the apartment state once it’s running.

Published by

Julian Birch

Full time dad, does a bit of coding on the side.

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