How to cancel asynchronous callback function in C++/WRL?

坚强是说给别人听的谎言 提交于 2019-12-08 05:22:28

IAsyncOperation<TResult> has a Cancel() method inherited from IAsyncInfo.

You cannot cancel the Completed handler itself. It is fired when the async operation is finished. You have to cancel the operation instead, and then the Completed handler reports the final status of the operation.

#include <Windows.Services.Store.h>
#include <wrl.h>

auto onAppLicCompletedCallback = Callback<Implements<RuntimeClassFlags<ClassicCom>, IAsyncOperationCompletedHandler<StoreAppLicense*>, FtmBase>>(
    [](IAsyncOperation<StoreAppLicense*>* operation, AsyncStatus status)
{
    //Asynchronous operation is done
    if (status == completed)
    {
        // use results from operation->GetResults() as needed...
    }
    return S_OK;
});

ComPtr<IAsyncOperation<StoreAppLicense*>> opAppLic;
// Begin asynchronous operation that assigns opAppLic...

opAppLic->put_Completed(onAppLicCompletedCallback.Get());

//Keep going ...

//Say, at some point here I need to cancel the operation...
opAppLic->Cancel();

Whoever also runs into this. I think I got it. Remy Lebeau was partially correct. What I needed to do was to obtain IAsyncInfo via QueryInterface as such:

ComPtr<IAsyncInfo> pAsyncInfo;
if(SUCCEEDED(opAppLic->QueryInterface(__uuidof(pAsyncInfo), &pAsyncInfo)) &&
    pAsyncInfo)
{
    if(SUCCEEDED(pAsyncInfo->Cancel()))
    {
        //Async op was now canceled
        //Also note that `onAppLicCompletedCallback` will be called
        //with `status` set to `Canceled`
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!