【问题标题】:Why second thread with ContinueWith option is not waiting for first thread's end?为什么带有 ContinueWith 选项的第二个线程不等待第一个线程的结束?
【发布时间】:2015-05-09 18:30:09
【问题描述】:

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

var finalTask = parent.ContinueWith( .. )

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

启动主线程 1
启动 ContinueWith 线程 2
0 0 0
结束 ContinueWith 线程 2
ContinueWith 线程是 完成的!
启动子线程 3
结束子线程 3
启动子线程 2
结束子线程 2
启动子线程 1
结束子线程 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!");

        }

【问题讨论】:

    标签: c# multithreading task


    【解决方案1】:

    问题是Task.Run。这将以TaskCreationOptions.DenyChildAttach 开始任务。

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

    See here 深入讨论差异。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      相关资源
      最近更新 更多