2014-09-10 64 views
0

你好人我有問題在線程中使用參數。問題是我把一個對象List<object>作爲線程數組的一個參數,迭代到列表列表(List<List<Object>>)的foreach循環中,並且有時它會複製參數(我已經檢查過在我放置它之前是否有重複的對象在一個線程中)。我的代碼是這樣的。有誰知道什麼是錯的?在此先感謝線程C中的重複參數#

foreach (List<object> list2 in list1) 
{ 

    threads[i] = new Thread(() =>DoWork(list2, nRetorno)); 
    threads[i].Name = "thread " + i; 
    threads[i].Start(); 
    Thread.Sleep(5); 
    i++; 
} 
+0

這一個涵蓋完全相同的問題,因爲你幾乎相同的示例代碼 - http://stackoverflow.com/questions/8898925/is-there-a-reason-for- cs-reuse-the-the-variable-in-a-foreach/8899347#8899347。它涵蓋了一些關於'foreach'和關閉的細節(與重複相同)。 – 2014-09-10 22:00:25

+0

感謝您的回答..我以爲我是與線程錯誤..但這顯然是主要問題..與更多的罪惡後果 – hexehell00 2014-09-10 22:43:11

回答

0

在C#中還有用foreach工作的一些奇怪的行爲,請嘗試使用引用變量,而不是在foreach一個樣:

foreach (List<object> list2 in list1) 
      { 
       var list = list2; 

       threads[i] = new Thread(() =>DoWork(list, nRetorno)); 
       threads[i].Name = "thread " + i; 
       threads[i].Start(); 
       Thread.Sleep(5); 
       i++; 
      } 
+0

感謝您的回答 – hexehell00 2014-09-10 22:42:04

0

你拉姆達捕捉list2變量而不是價值。它複製到本地第一:

  foreach (List<object> list2 in list1) 
      { 
       List<object> list3 = list2; 
       threads[i] = new Thread(() =>DoWork(list3, nRetorno)); 
       threads[i].Name = "thread " + i; 
       threads[i].Start(); 
       Thread.Sleep(5); 
       i++; 
      } 
+0

感謝您的答案 – hexehell00 2014-09-10 22:42:21