CoMarshalInterThreadInterfaceInStream使用

330 篇文章 4 订阅 ¥19.90 ¥99.00
本文详细介绍了如何使用 CoMarshalInterThreadInterfaceInStream 将 IServiceProvider 接口从主线程 marshaling 到后台线程。在主线程的 SetSite 调用中,将 IServiceProvider 接口转换为可共享的 IStream 对象。在后台线程中,当需要访问 IServiceProvider 时,通过调用 CoGetInterfaceAndReleaseStream 获取适用于当前线程的代理接口。请注意,此操作只能执行一次,因此要缓存返回的接口以便后续使用。
摘要由CSDN通过智能技术生成
 
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 );
 }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值