2015-05-04 77 views
0
for (long key = 0; key < 5; key++) 
{ 
var processingThread = new Thread(() => Setup(key)); 
processingThread.Start(); 
} 

我想每個鍵值,但在同一時間對多個窗口執行Setup(key)功能..我如何執行多個線程具有相同的功能,但不同的參數同時

+4

會發生什麼?你被[關閉循環變量]咬了(http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful的.aspx)? –

+0

看看[ParameterizedThreadStart(https://msdn.microsoft.com/en-us/library/system.threading.parameterizedthreadstart%28v=vs.110%29.aspx) – Yoav

+2

暫時不100%肯定我明白了什麼你正試圖實現,我認爲Parallel.For可以在這種情況下使用。參見[here](https://msdn.microsoft.com/en-us/library/dd460713(v = vs.110).aspx) ,和[這裏](http://stackoverflow.com/questions/12405938/save-time-with-parallel-for-loop)。 –

回答

-1

退房的Parallel.ForEach()Parallel.For()方法。

https://msdn.microsoft.com/en-us/library/dd460720(v=vs.110).aspx

顯式地創建一個新的線程有大的開銷,應當避免。只有在有充分理由並且已經考慮使用基於線程池的解決方案(如PTL或類似方法)時纔可以這樣做。 (如果需要的話和鑄造)

-1
for (long key = 0; key < 5; key++) 
{ 
    var processingThread = new Thread(Setup); 
    processingThread.Start(key); 
} 

Setup參數類型必須更改爲object

+0

安裝程序實際上是一種方法,它接受循環變量作爲參數。 –

+0

當然。它的簽名大概是「void Setup(long key)」,不是嗎?它需要在「無效設置(對象鍵)」中進行更改。 – MatteoSp

+0

如何啓動線程一次,使其循環,並執行每次迭代Thread.sleep(500)? –

-2

如果Parallel.For()不提供的伎倆,你可以通過他們的一個的AutoResetEvent。
呼叫Wait()在所有的代表,然後創建的所有線程調用後Set()
,該系統確實

// THIS ISN'T TESTED AND IS WRITTEN HERE, SO MIND THE SYNTAX, THIS MIGHT NOT COMPILE !! 

AutoResetEvent handle = new AutoResetEvent(true); 

for (long key = 0; key < 5; key++) 
{ 
    var processingThread = new Thread(() => 
     { 
      handle.Wait(); 
      Setup(key) 
     }); 
    processingThread.Start(); 
} 

handle.Set(); 
+0

我在我的智能手機上撰寫了這篇文章,而不是在Visual Studio中。我在答案中提到了這一點。總的想法起作用。我把它作爲Parallel的替代品。For 如果有人記下。請統計他的理由.. –

0

請留意了這樣的事實,你需要用時間for循環中捕捉到的key本地副本,否則線程實際調用Setupkey已經成爲價值5。如果您捕獲本地副本,則該值不會更改,並且全部按預期工作。

for (long key = 0; key < 5; key++) 
{ 
    var localKey = key; 
    var processingThread = new Thread(() => Setup(localKey)); 
    processingThread.Start(); 
} 
相關問題