2013-10-12 76 views
0

說我的主線程調用一個循環,該循環會創建新線程並在某些其他函數上啓動它們。我如何確保在所有線程完成執行後執行語句

for (int i = 0; i < numberOfThreads; i++) 
{ 
     Thread thread = new Thread(start); 
     thread.Start(); 
} 
call_This_Function_After_All_Threads_Have_Completed_Execution(); 

我如何確保我的方法在所有其他線程完成執行後才被調用。

+5

['Task'(HTTP: //msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx)將使您的生活更輕鬆。 :) – Leri

+0

看看這篇文章:http://stackoverflow.com/questions/1584062/how-to-wait-for-thread-to-finish-with-net – JohnLBevan

回答

1

您可以使用AutoResetEvent-s。聲明一個AutoResetEvent數組,所有線程都可以訪問它。

AutoResetEvent[] events = new AutoResetEvent[numberOfThreads]; 

啓動線程這樣的:

for (int i = 0; i < numberOfThreads; i++) 
{ 
    events[i] = new AutoResetEvent(false); 
    Thread thread = new Thread(start); 
    thread.Start(i); 
} 
WaitHandle.WaitAll(events); 
call_This_Function_After_All_Threads_Have_Completed_Execution(); 

最後不要忘記調用線程設置()方法:

void start(object i) 
{ 
     //... do work 
     events[(int) i].Set(); 
} 
相關問題