如何使代理线程STA [英] How to make delegate thread STA

查看:159
本文介绍了如何使代理线程STA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到有关这个话题的一些讨论,并得出结论,这是不可能的。我应该使用线程,使其成为STA,当我需要结果时,连接主线程与创建的线程。这可以工作,但它不是一个理想的解决方案,因为使用代理我可以实现纯异步行为(使用回调)。所以,在我开始实现我自己的Future类之前(如在Java中)一样 - 有没有更好的方式来实现这个使用代表?

I have see some discussion around this topic and concluded that it is not possible. I should use Threads, make it STA and when I need result back, join main thread with the created thread. This can work but it is not an ideal solution as using delegates I can achieve pure asynchronous behavior (using callback). So, to square one - just before I start implementing my own Future class (as in Java); Is there a better way to achieve this using delegates?


   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
   }


推荐答案

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

It is not possible. A delegate's BeginInvoke() method always uses a threadpool thread. And TP threads always are MTA, that cannot be changed. To get an STA thread, you must create a Thread and call its SetApartmentState() method before starting it. This thread must also pump a message loop, Application.Run(). The COM object only uses it when its instance was created in that thread.

不知道您尝试做什么,但尝试多线程一段代码不是线程安全只是不能工作。 COM强制执行。

Not sure what you are trying to do, but trying to multi-thread a chunk of code that is not thread-safe just can't work. COM enforces that.

这篇关于如何使代理线程STA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆