2011-11-29 37 views
0

我在C#中的下一個代碼,.NET 4.0和Windows 7C#:睡一個線程塊其他?

class Program 
{ 
    static void Main(string[] args) { 
     DateTime startTime = DateTime.Now; 
     Parallel.For(1, 100, ind => { 
      System.Console.WriteLine("IND => " + ind + "; DEMORA: " + (DateTime.Now - startTime).TotalMilliseconds); 
      Thread.Sleep(1000); 
     }); 
     Console.Write("\nPresione una tecla para finalizar..."); 
     Console.ReadKey(true); 
    } 
} 

代碼的輸出與此類似:

IND => 8; DEMORA: 6001,9531 
IND => 31; DEMORA: 6002,9297 
IND => 55; DEMORA: 6006,8359 
IND => 12; DEMORA: 6008,789 
IND => 80; DEMORA: 6009,7656 
IND => 57; DEMORA: 6009,7656 
IND => 79; DEMORA: 6010,7422 
IND => 34; DEMORA: 6011,7187 
IND => 16; DEMORA: 6010,7422 
IND => 19; DEMORA: 7001,9531 
IND => 35; DEMORA: 7002,9297 
IND => 59; DEMORA: 7006,8359 
IND => 43; DEMORA: 7008,789 
IND => 81; DEMORA: 7009,7656 
IND => 58; DEMORA: 7010,7422 
IND => 67; DEMORA: 7011,7187 
IND => 83; DEMORA: 7011,7187 
IND => 17; DEMORA: 7012,6953 
IND => 20; DEMORA: 8001,9531 
IND => 36; DEMORA: 8002,9297 
IND => 60; DEMORA: 8006,8359 
IND => 44; DEMORA: 8008,789 
IND => 82; DEMORA: 8009,7656 
IND => 71; DEMORA: 8009,7656 
IND => 72; DEMORA: 8010,7422 
IND => 68; DEMORA: 8011,7187 
IND => 84; DEMORA: 8011,7187 
IND => 18; DEMORA: 8012,6953 

正如你所看到的,在程序運行的組每秒9,10線程(大約)。我不明白這是爲什麼。我瞭解阻塞線程不應該影響其他人的執行。因此,問題不應該是對Thread.Sleep的調用。

但是,如果我刪除線 '了Thread.Sleep(1000)' 我得到以下的輸出:

IND => 78; DEMORA: 20,5078 
IND => 79; DEMORA: 21,4844 
IND => 69; DEMORA: 18,5547 
IND => 53; DEMORA: 19,5312 
IND => 97; DEMORA: 20,5078 
IND => 80; DEMORA: 24,414 
IND => 9; DEMORA: 13,6719 
IND => 70; DEMORA: 26,3672 
IND => 10; DEMORA: 29,2969 
IND => 11; DEMORA: 29,2969 
IND => 12; DEMORA: 30,2734 
IND => 13; DEMORA: 30,2734 
IND => 14; DEMORA: 31,25 
IND => 15; DEMORA: 32,2265 
IND => 71; DEMORA: 29,2969 
IND => 72; DEMORA: 32,2265 

該輸出像我預期的

任何解釋?

感謝, 問候

+0

它肯定會影響其他線程的執行,線程池調度程序的工作是確保沒有太多的線程同時運行,並且如果線程沒有調度額外的線程(超出您擁有的核心數)沒有及時完成。在.NET 4中添加了自動調整算法 –

+0

我改變了上面的代碼以添加邏輯來計算併發運行的最大線程數。如果我增加睡眠時間,併發線程的數量也會增加。我還注意到,線程的開始時間爲1秒(aprox),以3-10爲一組。我可以改變這種行爲? – RemeR

回答

0

你單獨睡覺每個線程。

+0

是的,但我不會睡其他線程。然後主線程應該在完成之前啓動所有線程(可能),對吧? – RemeR

+0

@RemeR:TPL使用線程池;它不會啓動100個線程。相反,它會重新使用現有的線程來處理剩下的項目。打印'Thread.CurrentThread.ManagedThreadId'以查看它是如何工作的。 – SLaks

3

任務並行庫不會立即啓動線程。它將在現有線程上安排執行或基於CPU數量創建新線程。因此,它看起來像在您的計算機上任務並行庫將使用10個線程並安排您的任務使用這些線程。

+0

謝謝。那麼,我必須假設在4核CPU的win7中,應用程序的最大線程數爲10?我可以配置這個嗎? – RemeR

+0

我不認爲這很簡單。我想因爲睡眠代碼TPL允許多達10個任務運行。有關如何執行任務的更多配置,您需要創建一個[任務計劃程序](http://msdn.microsoft.com/zh-cn/library/dd997402.aspx) – Simon