2015-05-09 53 views
2

爲什麼第二THEAD通過線爲什麼使用ContinueWith選項的第二個線程不在等待第一個線程的結束?

var finalTask = parent.ContinueWith(..) 

開始不等待第一個線程的結束?這是打印證明,新線程不會等待第一個結束:

開始主線程1
開始ContinueWith線程2
結束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!"); 

     } 

回答

4

問題是Task.Run。這用TaskCreationOptions.DenyChildAttach開始任務。

使用Task.Factory.StartNew進行簡單更改即可解決問題。這是因爲這裏的默認值是TaskCreationOptions.None

See here深入討論了區別。

+0

好吧,它的工作;),謝謝:) –

相關問題