我正在使用C++/WRL编写Windows 10 Store / WinRT代码。我很想知道如何取消长期待定的异步操作?
说明它的最好方法是使用这个例子:
#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
return S_OK;
});
//'opAppLic' is defined as:
// ComPtr<IAsyncOperation<StoreAppLicense*>> opAppLic;
// ...
//Begin asynchronous operation
HRESULT hr = opAppLic->put_Completed(onAppLicCompletedCallback.Get());
if (SUCCEEDED(hr))
{
//Keep going ...
//Say, at some point here I need to cancel 'onAppLicCompletedCallback'
//but how do I do it?
}
编辑:当我尝试按照下面的答案中的建议添加opAppLic->Cancel()
时,它给了我以下编译错误:
1>file-name.cpp(597): error C2039: 'Cancel' : is not a member of 'Microsoft::WRL::Details::RemoveIUnknownBase<T>'
1> with
1> [
1> T=ABI::Windows::Foundation::IAsyncOperation<ABI::Windows::Services::Store::StoreAppLicense*>
1> ]
我需要QueryInterface
代替IAsyncInfo
,还是什么?
EDIT2:这就是我对opAppLic
变量的类型所得到的:
不,它没有Cancel
方法:
答案 0 :(得分:1)
IAsyncOperation<TResult>
的Cancel()
方法继承自IAsyncInfo
。
您无法取消Completed
处理程序本身。异步操作完成时会触发它。您必须取消操作,然后Completed
处理程序报告操作的最终状态。
#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();
答案 1 :(得分:1)
谁也遇到了这个问题。我想我明白了。 Remy Lebeau 部分正确。我需要做的是通过IAsyncInfo
获取QueryInterface
:
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`
}
}