Windows 并发运行时任务计划,但有例外



根据MSDN,

基于任务的延续始终计划在前置任务完成时执行,即使前置任务被取消或引发异常也是如此。

我不明白这一点,因为我尝试了以下代码,当第一个任务通过抛出异常完成时,不会调用后续任务。我理解为什么它必须将调用转发到调用concurrency::task::wait的站点,但我不明白 MSDN 上的声明是什么意思。我误解了什么?

#include <iostream>
#include <ppl.h>
#include <ppltasks.h>
int main(int argc, char* argv[])
{
using namespace std;
concurrency::task<void> task;
auto task_ticket = concurrency::create_task([]()
{
// A continuation task executed asynchronously
// after the previous task has completed. This
// is executed even if the previous task fails
// by being cancelled or throwing an exception.
throw std::runtime_error("Hello");
})
.then([]()
{
// This should be executed even though the
// previous task failed.
cout << "Task (2) executed" << endl;
});
try
{
task_ticket.wait();
}
catch (std::exception const& e)
{
cout << "Exception caughtn";
}
return EXIT_SUCCESS;
}

你误解了基于价值的延续与基于任务的延续。

给定返回类型为 T 的任务对象,您可以为其延续任务提供 T 或任务类型的值。采用类型 T 的延续称为基于值的延续。

您最初调用 create_task 返回task<void>。您传递给.then的 lambda 接受void作为输入(因为.then([]()等效于.then([](void)(,因此延续是基于值的,如果先行任务抛出,则不会运行。

要声明基于任务的延续,请使用:

auto task_ticket = concurrency::create_task([]()
{
throw std::runtime_error("Hello");
})
.then([](task<void> antecedent_task)
{
cout << "Task (2) executed" << endl;
antecedent_task.get(); // re-throws std::runtime_error
});

最新更新