2015-10-04 37 views
2

我有3點方法的名稱(步驟1,步驟2,步驟3),以及其中的一個具有密集的計算。 我情況怎麼樣第一步和第二步是相互獨立的,和第三步只能第一步應用程序不等待完成任務

這是我的代碼

static void Main(string[] args) 
{ 
    Console.WriteLine("Step1, Step2and Step3are independent of each other.\n"); 

    Console.WriteLine("Step1 and Step2 are independent of each other, and Step3 can be run only after Step1\n \n"); 
    Console.WriteLine("Step1 and Step2 are independent of each other, and Step3 can be run only after Step1 and Step2 finish.\n \n"); 
    Console.WriteLine(" Step1 and Step2 are independent of each other, and Step3 can be run only after Step1 or Step2 finishes.\n \n"); 

    var getCase = Int32.Parse(Console.ReadLine()); 
    switch (getCase) 
    { 
     case 1: 
      Parallel.Invoke(Step1, Step2, Step3); 
      break; 
     case 2: 
      Task taskStep1 = Task.Run(() => Step1()); 
      Task taskStep2 = Task.Run(() => Step2()); 
      Task taskStep3 = taskStep1.ContinueWith((previousTask) => Step3()); 
      Task.WaitAll(taskStep2, taskStep3); 
      break; 
     case 3: 
      Task step1Task = Task.Run(() => Step1()); 
      Task step2Task = Task.Run(() => Step2()); 
      Task step3Task = Task.Factory.ContinueWhenAll(
      new Task[] { step1Task, step2Task }, 
      (previousTasks) => Step3()); 
      step3Task.Wait(); 
      break; 
     case 4: 
      Task TaskStep1 = Task.Run(() => Step1()); 
      Task Taskstep2 = Task.Run(() => Step2()); 
      Task Taskstep3 = Task.Factory.ContinueWhenAny(
      new Task[] { TaskStep1, Taskstep2 }, 
      (previousTask) => Step3()); 
      Taskstep3.Wait(); 
      break; 
    } 


    Console.ReadLine(); 
} 


static void Step1() 
{ 
    Console.WriteLine("Step1"); 
} 
static void Step2() 
{ 
    double result = 10000000d; 
    var maxValue = Int32.MaxValue; 
    for (int i = 1; i < maxValue; i++) 
    { 
     result /= i; 
    } 
    Console.WriteLine("Step2"); 
} 
static void Step3() 
{ 
    Console.WriteLine("Step3"); 
} 

在案例2中,我得到的輸出僅第一步之後運行步驟3.

凡爲我寫的代碼來等待所有線程完成自己的工作。所以輸出應該是這樣的步驟1,步驟3,步驟2

+0

在LINQPad運行此,我無法重現你的問題。我得到了預期的產出。 –

+0

我同意,這似乎是沒有問題的情況下,2只是等待幾秒鐘,'Step2'將完成。只有在'Step2'之後,'Task.WaitAll'按照計劃完成。 –

回答

0

我測試你的代碼,它工作得很好,問題是,迭代從1到Int32.MaxValue需要很長的時間(約我的電腦上15秒),在此下面的代碼:

static void Step2() 
{ 
    double result = 10000000d; 
    var maxValue = Int32.MaxValue; 
    for (int i = 1; i < maxValue; i++) 
    { 
     result /= i; 
    } 
    Console.WriteLine("Step2"); 
} 

變化Int32.MaxValue到3000000,您將看到您預期的結果。