原文地址:devblogs.microsoft.com/oldnewthing…
原文作者:devblogs.microsoft.com/oldnewthing…
发布时间:2020年7月3日
上一次,我们研究了在C++/CX中如何用PPL和显式连续来投射任务取消。但是,在C++/CX中,如何使用PPL和coroutines呢?
auto picker = ref new FileOpenPicker();
picker->FileTypeFilter.Append(L".txt");
cancellation_token_source cts;
call<bool> do_cancel([cts](bool) { cts.cancel(); });
timer<bool> delayed_cancel(3000U, false, &do_cancel);
delayed_cancel.start();
StorageFile^ file;
try {
file = co_await create_task(picker->PickSingleFileAsync(), cts.get_token());
} catch (task_canceled const&) {
file = nullptr;
}
if (file != nullptr) {
DoSomething(file);
}
请注意,coroutine为我们省去了很多设置调用和定时器的麻烦,因为对象活在coroutine框架中,它一直存在,直到coroutine完成。
再次,任务在取消时抛出一个task_canceled。这次是因为任务 awaiter 的 await_resume,你可以在 pplawait.h 中找到它。
template <typename _Ty>
struct _Ppltask_awaiter {
...
decltype(auto) await_resume() {
return _Task.get();
}
};
但是等等,PPL库也支持在原始的AsyncAction^和AsyncOperation^对象上进行等待。下一次,我们将看看在这种情况下会发生什么。