我可以修改 BeginInvoke 我的委托的线程的性质吗?

发布于 2024-11-01 02:34:09 字数 558 浏览 2 评论 0原文

我正在实现一个具有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

说好的呢 2024-11-08 02:34:09

如果您的类按照接口实现这些 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文