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.