c++ - 如何取消C++/WRL中的异步回调函数?

标签 c++ windows-runtime windows-10 windows-store wrl

我正在使用 C++/WRL 编写 Windows 10 应用商店/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 变量类型:

enter image description here

不,它没有 Cancel 方法:

enter image description here

最佳答案

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();

关于c++ - 如何取消C++/WRL中的异步回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40201439/

相关文章:

c++ - 如何防止多播套接字接收单播数据

windows-runtime - 保留 WinRT 应用程序设置的最佳方法?

c# - 垂直滑动模拟鼠标事件发送到 Windows 10 平板电脑上的 Windows 窗体应用程序中的错误控件

C++ - 是否需要类原型(prototype)?

c++ - 性能调优

c# - Windows 运行时应用中的行为

c# - 模拟 Windows 8 应用商店应用程序购买

r - Shiny 应用 : Connection Reset By Peer

c# - x :Bind syntax for event binding giving error CS0122: inaccessible due to protection level

c++ - 调用重载运算符时出现歧义