如何使委托线程成为STA

kar*_*hul 3 c# delegates threadpool

我看到了一些围绕这个主题的讨论,并得出结论:这是不可能的。我应该使用线程,将其设为 STA,当我需要返回结果时,将主线程与创建的线程连接起来。这可以工作,但它不是一个理想的解决方案,因为使用委托我可以实现纯异步行为(使用回调)。所以,首先——就在我开始实现我自己的 Future 类(如 Java 中)之前;有没有更好的方法使用委托来实现这一目标?


   private delegate String DelegateFoo(String[] input);
   private String Foo(String[] input){
      // do something with input
      // this code need to be STA
      // below code throws exception .. that operation is invalid
      // Thread.CurrentThread.SetApartmentState(ApartmentState.STA)
      return "result";
   }

   private void callBackFoo(IAsyncResult iar){
      AsyncResult result = (AsyncResult)iar;
      DelegateFoo del = (DelegateFoo)result.AsyncDelegate;
      String result = null;
      try{
          result = del.EndInvoke(iar);
      }catch(Exception e){
          return;        
      }

      DelegateAfterFooCallBack callbackDel = new DelegateAfterFooCallBack (AfterFooCallBack);
      // call code which should execute in the main UI thread.
      if (someUIControl.InvokeRequired)
      {   // execute on the main thread.
         callbackDel.Invoke();
      }
      else 
      {
         AfterFooCallBack();
      }
   }
   private void AfterFooCallBack(){
       // should execute in main UI thread to update state, controls and stuff
   }

Run Code Online (Sandbox Code Playgroud)

Han*_*ant 5

这不可能。委托的 BeginInvoke() 方法始终使用线程池线程。并且TP线程始终是MTA,无法更改。要获得 STA 线程,您必须创建一个 Thread 并在启动它之前调用其 SetApartmentState() 方法。该线程还必须泵送消息循环Application.Run()。COM 对象仅在该线程中创建其实例时才使用它。

不确定您要做什么,但尝试对一段非线程安全的代码进行多线程处理是行不通的。COM 强制执行这一点。