在.NET应用程序中,我使用第三方ActiveX控件连接到设备。此组件没有UI,因此我可以从Windows应用程序,控制台应用程序或Windows服务使用。问题是它的行为因应用程序类型而异。
在控制台应用程序(或Windows服务)中使用它:
但是,从Windows应用程序中使用它时:
有没有办法隔离组件,以便调用在UI之外的线程中执行?
谢谢!
答案 0 :(得分:1)
经过长时间的搜索和阅读,我能够让它发挥作用。这是我使用的代码,带有一些注释。要了解更多信息,请搜索Google“.net Com thread sta”或类似信息。
// COM objects will always execute in the same thread where they were created,
// so it's better to create them in another thread (that must be alive as long as the object
// exists) to avoid blocking the UI thread.
var thread = new Thread(CreateComponent);
thread.SetApartmentState(ApartmentState.STA);
threads.Add(thread);
thread.Start("optional parameters");
private void CreateComponent(object obj)
{
var parameters = obj as string;
// Create the COM object here
var component = new CreateYourCOMComponent(parameters);
// You might want to catch all unhandled exceptions too
Application.ThreadException += Application_ThreadException;
// Once the object is created, the thread must be alive during
// the whole time the COM object remains alive. The Application.Run
// will pump the messages required for COM and prevent the thread for exiting.
Application.Run();
}