2011-12-14 144 views
0

主要問題是:如何在後臺(類似於BackgroundWorker的)幾個線程運行中TestingButton_Click的代碼,所以我將能夠:
1.獲取所有的原始數據的方法
2 。同時取消所有線程的測試
3.報告進度
4.將所有結果表檢索到主線程。在後臺運行並行

下面的代碼是內TestingButton_Click

List<Thread> threads = new List<Thread>(); 

      //Testing for each pair 
      foreach (InterfaceWithClassName aCompound in Group1) 
      { 
       foreach (InterfaceWithClassName bCompound in Group2) 
       { 
        InstancePair pair = new InstancePair(); 
        //some code 

        if (testModeParallel) 
        { 
         Thread thr = new Thread(TestPairParallel); 
         thr.Start(pair); 
         threads.Add(thr); 
        } 

        else 
        { 
         Thread thr = new Thread(TestPairSerial); 
         thr.Start(pair); 
         threads.Add(thr); 
        } 
       } 
      }    

      while (true) 
      { 
       int i = 0; 

       foreach (Thread thread in threads) 
       { 
        if (thread.IsAlive) 
         break; 

        i++; 
       } 

       if (i == threads.Count) 
        break; 

       Thread.Sleep(1000); 
      } 
      pairsResultsDataGrid.ItemsSource = tab.DefaultView 

用戶能夠選擇什麼化合物每次我有不同的數字對測試的時間來測試等等。 我對不同的方法TestPairSerial()和TestPairParallel()以防萬一。

TestPairSerial()結構是

 do 
     { 
      do 
      { 

      } while (isSetbCompaundParams); 

     } while (isSetaCompaundParams); 

     //filling up results into tables (main window variables) later to be connected to DataGrids 

TestPairParallel()與InfinitePartitioner實現並採用類似的結構只能用Parallel.ForEach(新InfinitePartitioner(),...

謝謝您的幫助。

+1

你的問題到底是什麼。你的第一句話沒有意義。提出一個問題。我建議您丟失背景信息,因爲它與您當前的問題無關。 – 2011-12-14 17:09:25

+0

查看[任務](http://msdn.microsoft.com/en-us/library/dd537609.aspx)類 – oleksii 2011-12-14 17:17:12

+0

請選擇一個問題,然後僅發佈與該問題相關的信息。 – Gabe 2011-12-14 17:17:32

回答

1

如何運行TestingButton_Click中的代碼在 背景中的多個線程中。

我會使用任務,因爲他們被設計爲做你想要的。

唯一的其他問題,我會回答,直到你得到更接近實際的解決方案是:

報告進度

有很多的方式來回報給定線程的進展,你將不得不訂閱一個事件,並編寫代碼來報告線程的進度。爲了更新窗體上的控件,這將需要您調用更改,這不是一個簡單的功能。

2

使用.NET 4.0的任務,而不是自己創建新線程。任務給你控制的粒度更細,可以很容易將數據傳遞到後臺運行,並等待整個畝成果提供了極好的支持如果需要,可以一次性執行併發任務並取消一切。強烈推薦。