How can I make a background worker thread set to Single Thread Apartment?
See the question and my original answer on StackOverflowBackgroundWorker uses by default a ThreadPool thread, but you can override this behavior. First you need to define a custom SynchronizationContext:
public class MySynchronizationContext : SynchronizationContext
{
public override void Post(SendOrPostCallback d, object state)
{
Thread t = new Thread(d.Invoke);
t.SetApartmentState(ApartmentState.STA);
t.Start(state);
}
}
And override the default SynchronizationContext, like this, before you use your BackgroundWorker:
AsyncOperationManager.SynchronizationContext = new MySynchronizationContext();
NOTE: this can have performance effects on the rest of your application, so you might want to restrict the new Post implementation (for example using the state or d parameters).