How can I make a background worker thread set to Single Thread Apartment?

前端 未结 5 938
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 07:34

I am creating an automated test running application. In this part of the application, I am working on a polling server. It works by constantly polling the web server to de

5条回答
  •  难免孤独
    2020-11-27 08:09

    BackgroundWorker 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).

提交回复
热议问题