我有一个在 STA EXE(调用CoInitialize(NULL)
)中实现的 COM 对象,我们称它为CMyObject
实现IControl
. 伪代码是这样的:
IControl
{
Start();
Stop();
};
CMyClass : IControl
{
public:
Start()
{
//create an ISomething in the main thread
mSomething = CoCreate(ISomething);
//this thread will make a call through ISomething
mThread = std::thread(ThreadMain, this);
}
Stop()
{
kill(mThread);
mSomething->Release();
}
UseSomething() //called from another thread
{
mSomething->DoStuff();
}
private:
std::thread mThread;
ISomething *mSomething;
};
void ThreadMain(CMyClass *o)
{
for(;;)
{
if(<some condition>)
o->UseSomething();
}
}
我的测试代码基本上遵循这种模式并且没有问题(到目前为止)但阅读STA 上的 MSDN表明我需要:
- 呼入
CoInitialize
/CoUninitialze
入ThreadMain
- 使用编组从工作线程调用接口
这个问题(如何从不同的公寓模型访问 COM 对象?)也表明需要编组并提倡使用 GIT。
然而,公寓模型是 COM 的一部分,我从来没有真正理解过,我想检查一下这在我的情况下是否必要 - 特别是因为它目前运行良好而没有抛出错误 - 我不想添加代码只是“万一需要,我不能说”。
如果有任何区别,那么ISomething
有问题的 COM 对象仅由工作线程调用,而不是由主线程调用。在我的具体情况下,CMyObject
任何时候都只会存在一个。