我怎样才能让一个后台工作线程设置为单线程公寓? [英] How can I make a background worker thread set to Single Thread Apartment?

查看:869
本文介绍了我怎样才能让一个后台工作线程设置为单线程公寓?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个自动化测试运行的应用程序。在应用程序中的这一部分,我正在轮询服务器上。它通过不断地轮询Web服务器,以确定新的自动化测试应该运行(我们的GUI应用程序的自动夜间运行)。

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 determine when a new automated test should be run (for nightly automated runs of our GUI application).

在轮询服务器看到一个请求时,它会下载所有必要的信息,然后执行在后台工作的试运行。问题是试运行的那部分具有OLE,COM,和其他电话(例如, Clipboard.Clear())发生在后台工作线程。当这些调用之一发生时,会出现以下异常:

When the polling server sees a request, it downloads all the information necessary and then executes the test run in a background worker. The problem is that part of the test run has OLE, COM, and other calls (for example, Clipboard.Clear()) that occur in the background worker thread. When one of these calls occurs, the following exception occurs:

当前线程必须设置为单线程单元(STA)模式OLE,可以调用之前。确保您的主要功能有请将STAThreadAttribute标记就可以了。

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.

我如何可以标记一个后台工作线程作为单线程公寓?在我的Program.cs主要呼叫显然已经拥有该属性。

How can I mark a background worker thread as single thread apartment? The Main call in my Program.cs obviously already has that attribute.

推荐答案

这是不可能的,BGW使用线程池线程。 TP线程总是MTA,它不能被改变。你将不得不使用普通线程,调用SetApartmentState()开始之前。此线程也应该抽消息循环,调用Application.Run()。

This is not possible, BGW uses a threadpool thread. TP threads are always MTA, it cannot be changed. You will have to use a regular Thread, call SetApartmentState() before you start it. This thread also should pump a message loop, call Application.Run().

也许你应该考虑调用从UI线程此code。因为在所有的可能性,COM服务器正在运行反正它的UI线程上的方法。从工作线程来创建COM服务器是自动的STA线程编组调用,COM照顾它。

Maybe you ought to consider calling this code from the UI thread. Because in all likelihood, the COM server is running its methods on the UI thread anyway. Marshaling calls from a worker thread to the STA thread that created the COM server is automatic, COM takes care of it.

或采取由不畏艰险和元帅自己。你可以创建自己的STA线程给服务器一个幸福的家。你会发现code在这个帖子,一定要在你的初始化()重写创建COM对象。

Or take the bull by the horns and marshal yourself. You can create your own STA thread to give the server a happy home. You'll find code in this post, be sure to create the COM object in your Initialize() override.

这篇关于我怎样才能让一个后台工作线程设置为单线程公寓?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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