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

标签 c# multithreading task

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

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/

相关文章:

javascript - 如何在 grunt .tmpl 文件中找出当前的构建任务

c# - 调用异步方法的两种方式。 C#

task - Blazor 任务延续的推荐指南

c# - 随机分配 Button 的内容

c# - 如何创建窗口服务并用于发送邮件

C# 控制台应用程序——尝试从 else 语句访问列表

c# - 带有 OOXML Excel 密码的 NPOI 不起作用

java - 不断更新 GUI 元素的最佳方法

c++ - 控制 OpenMP 程序中的 FPU 行为?

c++ - 如何重载操作数 << 以像 ostream 样式一样使用