CoMarshalInterThreadInterfaceInStream使用

330 篇文章 4 订阅 ¥19.90 ¥99.00
 
You have to marshal the IServiceProvider interface from your main thread to your background thread.
 
In your SetSite call (which is guaranteed to be called on the main UI thread), marshal the IServiceProvider interface into a shared stream ( IStream ) object using CoMarshalInterThreadInterfaceInStream . You’ll need to make sure that this shared object can be accessed from both threads. In your background thread, when you need to get at the IServiceProvider , call CoGetInterfaceAndReleaseStream to get back a proxied IServiceProvider that works for the calling thread. Note that you can call this only once, so cache the interface that you get back. You can then call through this interface to QueryService . See the example code below:
 
class CMyPackage : public IVsPacakge
{
private :
 CComPtr< IStream > m_pSPStream; // Used to marshal IServiceProvider between threads
 CComPtr< IServiceProvider > m_pBackgroundSP; // IServiceProvider proxy for the background thread
 
public :
 HRESULT SetSite( IServiceProvider* pSP )
 {
    // Marshal the service provider into a stream so that
    // the background thread can retrieve it later
    CoMarshalInterThreadInterfaceInStream(IID_IServiceProvider, pSP, &m_pSPStream);
 
    //... do the rest of your initialization
 }
 
 // Call this when your background thread needs to call QueryService
 // The first time through, it unmarshals the interface stored
 HRESULT QueryServiceFromBackgroundThread(
    REFGUID rsid,     // [in] Service ID
    REFIID riid,      // [in] Interface ID
    void **ppvObj     // [out] Interface pointer of requested service (NULL on error)
 {
    if( !m_pBackgroundSP )
    {
      if( !m_pSPStream )
      {
        return E_UNEXPECTED;
      }
 
      HRESULT hr = CoGetInterfaceAndReleaseStream( m_pSPStream, IID_IServiceProvider, (void **)&m_pBackgroundSP );
      if( FAILED(hr) )
      {
        return hr;
      }
 
      // The CoGetInterfaceAndReleaseStream has already destroyed the stream.
      // To avoid double-freeing, the smart wrapper needs to be detached.
      m_pSPStream.Detach();
    }
 
    return m_pBackgroundSP->QueryService( rsid, riid, ppvObj );
 }
};
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值