2017-03-01 54 views
3

我沒有什麼問題。循環的不同行爲

我的輸入: 配置 - 包含此刻2個不同對象的集合。

結果看起來就像被執行了兩次,但具有相同參數。如果在循環內部放置斷點,我會看到不同的對象。我做錯了什麼?

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

    foreach (var configuration in configurations) 
    { 
     Thread thread = new Thread(() => new DieToolRepo().UpdateDieTool(configuration)); 
     thread.Start(); 
     threads.Add(thread); 
    } 

    threads.WaitAll(); 

預期結果: enter image description here

我有什麼:

enter image description here

+1

你對「結果看起來像執行了兩次,但具有相同的參數」是什麼意思? 請向我們展示整個代碼和您的預期/實際輸出。此外,粘貼代碼而不是放置圖像 –

+0

由於@NahuelIanni問,請顯示代碼爲'DieToolRepo' –

回答

4

有disambiguition與變量 '配置'。

繼@ HenkHolterman的意見,我先發佈一個更清潔,更精確的,解決方法:

List<Thread> threads = new List<Thread>(); 
foreach (var configuration in configurations) 
{ 
    var threadConfiguration = configuration; 
    Thread thread = new Thread(() => DieToolRepo().UpdateDieTool(threadConfiguration); 
    thread.Start(); 
    threads.Add(thread); 
} 
threads.WaitAll(); 

此外,您還可以做得出來的for循環:

List<Thread> threads = new List<Thread>(); 
for (var index=0; index< configurations.Length; index++) 
{ 
    Thread thread = new Thread(() => DieToolRepo().UpdateDieTool(configurations[index])); 
    thread.Start(); 
    threads.Add(thread); 
} 
threads.WaitAll(); 

出現這種情況因爲變量'配置'對於所有線程是相同的,當它運行時。 使用此方法將創建索引(localIndex - 按值複製)的新副本,因此共享使用配置將爲每次調用提供不同的配置。

,我敢肯定有一個更好的方式來處理這些線程,並且相應地使用更安全值。

+1

誰downvoted,你能解釋爲什麼嗎? –

+1

我不知道你爲什麼得到「 - 」,因爲用「for」循環一切工作完美 –

+0

謝謝:)在這種情況下,你可以請標記爲已解決? (我遇到過這種確切的問題,所以我知道這會解決這個問題) –