gpt4 book ai didi

c# - 嵌套任务和子任务有什么区别

转载 作者:太空狗 更新时间:2023-10-30 00:10:41 30 4
gpt4 key购买 nike

我想了解嵌套任务和子任务之间的区别。

var outerTask = Task.Factory.StartNew( () => 
{
var nestedTask = Task.Factory.StartNew( () =>
{
Console.WriteLine("Inside nestedTask");
});
});


A "child task" looks like this:

var parentTask = Task.Factory.StartNew( () =>
{
var childTask = Task.Factory.StartNew( () =>
{
Console.WriteLine("Inside childTask");
}, TaskCreationOptions.AttachedToParent );
});

这里附上代码

似乎当我们开始任何嵌套任务时,外部任务可能会在内部任务之前完成,但在子任务的情况下,子任务总是在父任务之前完成。我不确定我是否正确。因此,如果有人指导我何时执行嵌套任务以及何时使用示例场景执行子任务,这将很有帮助。谢谢

最佳答案

IMO,最好的解释在Stephen Toub's blog post :

... the Task being created registers with that parent Task as a child,leading to two additional behaviors: the parent Task won’t transitionto a completed state until all of its children have completed as well,and any exceptions from faulted children will propagate up to theparent Task (unless the parent Task observes those exceptions beforeit completes).

关于c# - 嵌套任务和子任务有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20048493/

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