相关疑难解决方法(0)

无法转换类型异常的COM对象

我有以下代码:

public void Test(IMyInterface iInterface)
{
  iInterface.CallMethod ( );
}
Run Code Online (Sandbox Code Playgroud)

哪个工作正常.但是,如果我将代码更改为线程:

private IMyInterface myInterface;
public void Test(IMyInterface iInterface)
{
  myInterface = iInterface;
  new Thread ( new ThreadStart ( CallInterfaceMethod) ).Start ( );
}

public void CallInterfaceMethod ( )
{
  myInterface.CallMethod ( )
}
Run Code Online (Sandbox Code Playgroud)

当我使用线程时,我收到异常:

无法将"System .__ ComObject"类型的COM对象强制转换为接口类型"IMyInterface".此操作失败,因为对于具有IID"{GUID}"的接口的COM组件的QueryInterface调用由于以下错误而失败:不支持此类接口

但是应该支持接口就好了吗?有人对这里发生的事情有任何想法吗?

c# com interface

20
推荐指数
1
解决办法
2万
查看次数

如何将消息发布到运行消息泵的STA线程?

因此,在此之后,我决定在专用的STA线程上显式实例化COM对象.实验表明COM对象需要一个消息泵,我通过调用它来创建Application.Run():

private MyComObj _myComObj;

// Called from Main():
Thread myStaThread = new Thread(() =>
{
    _myComObj = new MyComObj();
    _myComObj.SomethingHappenedEvent += OnSomthingHappened;
    Application.Run();
});
myStaThread.SetApartmentState(ApartmentState.STA);
myStaThread.Start();
Run Code Online (Sandbox Code Playgroud)

如何从其他线程发布STA线程的消息泵消息?

注意: 为了简洁起见,我对问题进行了大量编辑.@Servy的答案的某些部分现在似乎无关紧要,但它们是针对原始问题的.

c# com interop message-queue sta

14
推荐指数
1
解决办法
8494
查看次数

标签 统计

c# ×2

com ×2

interface ×1

interop ×1

message-queue ×1

sta ×1