单线程单元模型 - 如何处理创建工作线程的COM对象?

时间:2015-11-10 18:55:19

标签: c++ com apartments

我有一个在STA EXE中实现的COM对象(调用CoInitialize(NULL)),我们称之为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();
 }
}

我的测试代码基本上遵循这种模式并且没有问题(到目前为止)但是阅读MSDN on STA建议我需要:

  • CoInitialize
  • 中致电CoUninitialze / ThreadMain
  • 使用编组从工作线程
  • 调用接口

这个问题(How to access COM objects from different apartment models?)也表明需要编组,并提倡使用GIT。

然而,公寓模型是COM的一部分我从来没有真正设法理解我想在我的情况下检查是必要的 - 特别是因为它目前工作得很好而没有抛出错误 - 我不想只是添加代码“万一它是需要的,我不知道”。

如果它有任何区别,那么有问题的COM ISomething对象仅由工作线程 调用,而不是由主线程调用。在我的具体情况下,任何时候都只会有一个CMyObject

0 个答案:

没有答案