【问题标题】:winrt/c++: await result from dispatched taskwinrt/c++:等待分派任务的结果
【发布时间】:2019-02-24 21:30:37
【问题描述】:

我想将作业分派到 UI 线程,然后等待结果并从另一个线程使用它。像这样,但是 co_await 在 lambda 中不起作用:

dispatcher.RunAsync(CoreDispatcherPriority::Normal, [&]() {
    auto res = co_await mStoreContext.RequestPurchaseAsync(L"");
});

或者甚至等待整个 RunAsync 操作,如果我能从中得到我的结果

【问题讨论】:

  • 更惯用的方式是co_await resume_foreground(dispatcher); auto res = co_await mStoreContext.RequestPurchaseAsync(L""); co_await resume_background(); use_result(res);

标签: c++ multithreading concurrency async-await winrt-async


【解决方案1】:

那是因为void 不能用作协程的返回值(如果你使用我的my library,我可以)。

尝试返回std::future<void>

dispatcher.RunAsync(CoreDispatcherPriority::Normal, [&]() -> std::future<void> {
    auto res = co_await mStoreContext.RequestPurchaseAsync(L"");
});

【讨论】:

  • 谢谢。更好的方法是从完整的 runasync 块中获取结果,但这很好用
  • 这很危险,因为引用捕获。在确定 lambda 已完成运行之前,调用方无法返回。
猜你喜欢
  • 2023-03-08
  • 2017-06-02
  • 1970-01-01
  • 2016-06-15
  • 2019-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多