经过长时间的搜索和阅读,我能够使它工作。这是我使用的代码,带有一些注释。要了解更多信息,请在 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();
}