2017-02-02 45 views
0

我想執行線程中的代碼,並等待for循環完成之前for循環後執行代碼。代碼正在運行之前for循環已完成,線程池c#

for (int i = 254; i > 1; i--) 
{ 

    //some code here... 

    WaitCallback func = delegate (object state) 
    { 
     //do something here.... - i want this to finish with the loop first 
    }; 

    ThreadPool.QueueUserWorkItem(func); 

} 

// this code is executed once the for loop has finished 
// however i want it to be done 
// after the thread has finished executing its code and the for loop. 
+0

那麼你想跨越254線程? – Tigran

+0

是的,我想這樣做...... – Milan

+0

@Tigran它使用線程池,所以它實際上不會使用254個線程。它只是調度由線程池以線程池認爲最優化的任何方式執行的254個操作,其不涉及254個實際線程。 – Servy

回答

7

您可以使用TPL排隊你的工作和循環之後調用Task.WaitAll

Task[] tasks = new Task[254]; 
for (int i = 254; i > 1; i--) 
{ 

    //some code here... 

    Task task = TaskFactory.StartNew(() => 
    { 
     //do something here.... - i want this to finish with the loop first 
    }); 
    tasks[i - 1] = task; 
} 

Task.WaitAll(tasks); 

// do other stuff 

TPL最終將使用線程池來執行工作。

PS。我沒有運行它或任何東西,所以在數組訪問中可能會出現錯誤的錯誤,但是您應該瞭解該方法背後的一般想法。

編輯

正如在評論中提到eocron,使用Parallel.For也可能是一種選擇。

+0

我會給這個前。謝謝你的努力。 – Milan

+0

使用Parallel.For(...)不是更好嗎? – eocron

+0

@eocron這取決於委託內部的代碼類型,不是嗎?但是,這絕對是另一種看待的方法。補充說,答案。 – MarcinJuraszek

相關問題