gpt4 book ai didi

c# - 为什么带有 ContinueWith 选项的第二个线程不等待第一个线程的结束?

转载 作者:行者123 更新时间:2023-11-30 20:43:45 25 4
gpt4 key购买 nike

为什么第二个主题是按行开始的

var finalTask = parent.ContinueWith( .. )

不是在等待第一个线程的结束吗?这是证明新线程没有等待第一个线程结束的打印输出:

Starting main thread 1
Starting ContinueWith thread 2
0 0 0
Ending ContinueWith thread 2
ContinueWith thread is finished!
Starting child thread 3
Ends child thread 3
Starting child thread 2
Ends child thread 2
Starting child thread 1
Ends child thread 1

代码:

public static void AttachTasksToMain()
{
Task<Int32[]> parent = Task.Run(() =>
{
Console.WriteLine("Starting main thread 1");
var results = new Int32[3];
new Task(() => {
Console.WriteLine("Starting child thread 1");
results[0] = 0;
Console.WriteLine("Ends child thread 1");
}, TaskCreationOptions.AttachedToParent).Start();

new Task(() => {
Console.WriteLine("Starting child thread 2");
results[1] = 1;
Console.WriteLine("Ends child thread 2");
}, TaskCreationOptions.AttachedToParent).Start();

new Task(() => {
Console.WriteLine("Starting child thread 3");
results[2] = 2;
Console.WriteLine("Ends child thread 3");
}, TaskCreationOptions.AttachedToParent).Start();

//this thread finishes when all child-thread are finished!
return results;
});
//parent.Wait();

var finalTask = parent.ContinueWith(parentTask =>
{
Console.WriteLine("Starting ContinueWith thread 2");
foreach (int i in parentTask.Result)
Console.WriteLine(i);

Console.WriteLine("Ending ContinueWith thread 2");
});

finalTask.Wait();
Console.WriteLine("ContinueWith thread is finished!");

}

最佳答案

问题是 Task.Run。这将使用 TaskCreationOptions.DenyChildAttach 启动任务。

使用 Task.Factory.StartNew 进行简单更改,问题就解决了。那是因为这里的默认值是 TaskCreationOptions.None

See here深入讨论差异。

关于c# - 为什么带有 ContinueWith 选项的第二个线程不等待第一个线程的结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30138699/

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