0

我在 DLL 中实现了一个函数,封装了对 Out-OF-Proc COM 服务器的异步调用。它看起来像这样:

    HRESULT hr = S_OK;
    bool bCoInitialized = false;
    IXXXXInterface* pServer = NULL;
    ISynchronize* pISynchronize = NULL;
    AsyncIXXXXInterface* pAsyncServer = NULL;
    ICancelMethodCalls* pICancel = NULL;

    hr = CoInitializeEx(NULL,COINIT_MULTITHREADED);
    if (hr == S_OK || hr == S_FALSE) {
        bCoInitialized = true;
    }
    else if(hr == RPC_E_CHANGED_MODE) {
        bCoInitialized = false;
    }
    else{
        bCoInitialized = false;
        goto cleanup
    }
    hr = CoCreateInstance(CLSID_XXXXInterface, NULL,
        CLSCTX_ALL|CLSCTX_ACTIVATE_64_BIT_SERVER, IID_IXXXXInterface, (void**)&pServer);
    if (FAILED (hr)) {
        goto cleanup
    }

    ICallFactory* pCallFactory;
    hr = pServer->QueryInterface (IID_ICallFactory, (void**) &pCallFactory);
    if (FAILED (hr)) {
        goto cleanup
    }

    hr = pCallFactory->CreateCall (IID_AsyncIXXXXInterface, NULL, IID_AsyncIXXXXInterface,
        (IUnknown**) &pAsyncServer);
    pCallFactory->Release();
    if (FAILED (hr)) {
        goto cleanup
    }

    hr = pAsyncServer->QueryInterface(IID_ISynchronize,  (void**) &pISynchronize);
    if (FAILED (hr)) {
        goto cleanup
    }

    hr = pAsyncServer->QueryInterface(IID_ICancelMethodCalls, (void**) &pICancel);
    if (FAILED (hr)) {
        goto cleanup
    }

    // Do something use the async interface.
cleanup:    
    if(pICancel)
        pICancel->Release();
    if(pISynchronize)
        pISynchronize->Release();
    if(pAsyncServer)
        pAsyncServer->Release();
    if(pServer)
        pServer->Release();
    if(bCoInitialized)     // If I comment out these 
        CoUninitialize();  // 2 lines, it will be OK.

问题是当我在多线程中调用该函数时,有时它会在 COM 的工作线程中使用调用堆栈在 combase.dll 中抛出异常。如果我只是注释掉最后两行,就可以了。看起来 CoUnitialize() 将释放所有资源,而 COM 线程池中的工作线程在某些情况下仍在使用它们。我不确定我的想法是否正确,或者其他地方有问题。如果我是对的,如何通过使用哪个 API 等待工作线程释放所有资源来避免这个问题?

4

0 回答 0