gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:45:36 26 4
gpt4 key购买 nike

根据 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 的初始调用返回 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
});

关于c++ - 有异常的 Windows 并发运行时任务调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45260620/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com