You need to enable JavaScript to run this app. 如何将带取消功能的C++/CX create_task转换为等效C++/WinRT代码
优惠活动
大模型
产品
解决方案
定价
更多

如何将带取消功能的C++/CX create_task转换为等效C++/WinRT代码

C++/CX 转 C++/WinRT 等效代码实现(含取消令牌逻辑)

前置准备

首先确认你已经引入了必要的头文件,且在MainPage类中声明取消令牌源成员:

// 头文件引入
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.UI.Popups.h>
#include <winrt/Windows.UI.Xaml.h>

// MainPage.h 中添加成员变量
winrt::cancellation_token_source cancellationTokenSource;

等效转换代码

// 按钮点击事件
winrt::fire_and_forget MainPage::OnButtonClick(winrt::Windows::Foundation::IInspectable const& sender, winrt::Windows::UI::Xaml::RoutedEventArgs const& args)
{
    using namespace winrt::Windows::UI::Popups;
    MessageDialog msgdlg{L"Choose a color", L"How To Cancel Async"};
    msgdlg.Commands().Append(UICommand{L"Red", nullptr, winrt::box_value(winrt::Windows::UI::Colors::Red())});
    // ... 其余命令添加逻辑和原有一致

    // 重置取消令牌源
    cancellationTokenSource = winrt::cancellation_token_source{};
    auto token = cancellationTokenSource.get_token();

    try
    {
        // 绑定取消令牌并等待弹窗操作结果
        auto command = co_await msgdlg.ShowAsync(token);
        // ... 原有弹窗返回后的正常处理逻辑
    }
    catch (winrt::hresult_canceled const&)
    {
        // 异步操作被取消后的处理逻辑,对应原有task.then中处理取消的分支
    }
}

// 计时器触发事件
void MainPage::OnTimerTick(winrt::Windows::Foundation::IInspectable const& sender, winrt::Windows::Foundation::IInspectable const& args)
{
    // 触发取消,和CX逻辑完全一致
    cancellationTokenSource.cancel();
}

关键逻辑说明

  • 取消令牌源获取:C++/WinRT 中直接构造 winrt::cancellation_token_source 实例即可,功能、API 和 C++/CX 中的 cancellation_token_source 基本对齐,通过 get_token() 获取关联的取消令牌,调用 cancel() 即可触发所有绑定该令牌的异步操作取消。
  • 异步操作绑定取消令牌:C++/WinRT 中所有自带的 IAsyncXxx 类型异步方法都支持直接传入取消令牌作为参数,替代原有 create_task 传令牌的逻辑。如果偏好使用 then 链式调用而非协程,也可以按照以下写法实现和原有CX完全一致的逻辑:
    msgdlg.ShowAsync(token).then([this](winrt::Windows::Foundation::IAsyncOperation<UICommand> const& op)
    {
        try
        {
            auto command = op.GetResults();
            // ... 原有处理逻辑
        }
        catch (winrt::hresult_canceled const&)
        {
            // 取消处理逻辑
        }
    });
    
  • 类型替换:C++/WinRT 中移除了 ^ 、ref new 等CX专属语法,所有运行时类直接值语义构造,Object^ 对应通用基类 winrt::IInspectable。

内容的提问来源于stack exchange,提问作者MRahilly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 23:54:05