我可以修改 BeginInvoke 我的委托的线程的性质吗?
我正在实现一个具有 BeginSomething()
和 EndSomething()
对的接口,并且我的实现位于方法 Execute()
中,
所以我创建一个 Action action = Execute
,并在 BeginSomething 中调用 action.BeginInvoke
,在 EndSomething 中调用 action.EndInvoke
。但是,我的 Execute 方法必须由单元状态为 STA(单线程单元)的线程调用。通常,这是通过调用 Thread.SetApartmentState< 来完成的/code>
,但在这种情况下我不知道哪个线程将调用我的方法。
我该如何让调用线程成为STA?
I am implementing an interface that has a BeginSomething()
and EndSomething()
pair, and my implementation is in a method Execute()
So I create an Action action = Execute
, and call action.BeginInvoke
in BeginSomething, and action.EndInvoke
in EndSomething. However my Execute method has to be called by a thread whose apartment state is STA (single-threaded apartment). Usually this is done by calling Thread.SetApartmentState
, but in this case I don't know which thread is going to invoke my method.
How should I make the calling thread STA?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的类按照接口实现这些 Begin/End 对方法,那么您可以控制工作的实际完成方式。我相信委托(其中 Action 是其类型化泛型)将使用默认线程池,因此将由共享的可重用可用线程执行。由于扰乱线程池是不可行的,因此在这种情况下直接委托是不行的。
您必须创建自己的 Thread 对象(将新的 ThreadStart 传递给您的方法)并按照您已经指示的方式设置它的单元状态。该方法必须有自己的回调方式,因为据我所知,普通线程没有提供方便的方法。
您还可以选择将 任务 与 < a href="http://blogs.msdn.com/b/pfxteam/archive/2010/04/07/9990421.aspx" rel="nofollow">自定义 StaTaskScheduler(如果您使用的是 .NET) 4.0,但这可能会带来更多的麻烦和/或复杂性,因为它增加了很多依赖项。不过,它确实消除了回调问题。
If your class is implementing those Begin/End pair methods as per an interface, then you have control over how the work is actually done. Delegates (of which Action is a typed generic of) will use the default thread pool I believe, and so will be performed by a shared re-usable available thread. Since messing with the thread pool isn't feasible, straight delegates are a no-go in this case.
You'll have to create your own Thread object (passing in a new ThreadStart to your method) and set it's apartment state as you've already indicated. That method is simply going to have to have its own way to callback, since vanilla Threads don't provide a convenient way to my knowledge.
You could also optionally use Tasks along with a custom StaTaskScheduler if you're using .NET 4.0, but this could be more trouble and/or complication than it's worth since it adds a lot of dependencies. It does eliminate the callback problem, though.