Windows 有异常的并发运行时任务调度

Windows concurrency runtime task scheduling with exceptions

根据MSDN

A task-based continuation is always scheduled for execution when the antecedent task finishes, even when the antecedent task is canceled or throws an exception.

我不明白这一点,因为我尝试了以下代码,当第一个任务通过抛出异常完成时,没有调用后续任务。我明白为什么它必须将调用转发到调用 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 caught\n";
    }
    return EXIT_SUCCESS;
}

你误会了Value-Based Versus Task-Based Continuations.

Given a task object whose return type is T, you can provide a value of type T or task to its continuation tasks. A continuation that takes type T is known as a value-based continuation.

您最初致电 create_task returns 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
});