簡體   English   中英

當所有主題完成時

[英]When All Threads Are Complete

這是我第一次使用多線程的真正嘗試,我想知道當我的所有任務組完成運行時我怎么知道:

for (int i = 0; i < taskGroups.Count(); i++) {
    ThreadStart t = delegate { RunThread(taskGroups[i]); };
    new Thread(t).Start();
}
if(allThreadsComplete){ //???

}

任何幫助將非常感激

附錄:

ThreadStart[] threads = new ThreadStart[taskGroups.Count()];
for (int i = 0; i < taskGroups.Count(); i++) {
    threads[i] = new ThreadStart[]
    threads[i] = delegate { RunThread(taskGroups[i]); };
    new Thread(t).Start();
}
bool threadsComplete = false;
while(!threadsComplete){
    for(int i=0;i<taskGroups.Count();i++){
        if(threads[i].State == complete)
        threadsComplete = true;
    }
}

您需要存儲所有線程,然后調用Thread.Join()。

像這樣的東西:

List<Thread> threads = new List<Thread>();
for (int i = 0; i < taskGroups.Count(); i++) {
   int temp = i; //This fixes the issue with i being shared
   Thread thread = new Thread(() => RunThread(taskGroups[temp]));
   threads.Add(thread);
   thread.Start();
}

foreach (var thread in threads) {
    thread.Join();
}

如果您使用的是3.5,那么您可以編寫自己的 CountdownEvent,如果您使用的是4.0,那么您可以使用內置的CountdownEvent來執行以下操作:

CountdownEvent = new CountdownEvent(taskGroups.Count());

for (int i = 0; i < taskGroups.Count(); i++) 
{
    int item = i; // copy i locally
    ThreadStart t = delegate 
    { 
        RunThread(taskGroups[item]); 
        latch.Signal();
    };
    new Thread(t).Start();
}

latch.Wait();

latch.Wait()將導致代碼阻塞,直到線程全部完成。 此外,您可能希望稍微更改啟動線程的方式:

CountdownEvent = new CountdownEvent(taskGroups.Count());

for (int i = 0; i < taskGroups.Count(); i++) 
{
    int item = i; // copy i locally
    Thread t = new Thread(()=>
    { 
        RunThread(taskGroups[item]); 
        latch.Signal();
    });
    t.IsBackground = true;
    t.Start();
}

latch.Wait();

請注意,我將線程設置為后台:這是您的應用程序從退出時掛起而不是所有線程都已完成(即防止ghost或守護程序線程)。

您可以檢查每個Thread對象的ThreadState屬性。

您可以使用Thread.Join確保每個單獨的線程都已完成運行。

您可以將公共靜態整數字段添加到主線程中,在每個子線程中,當它完成時將其增加1,然后在主線程中等待(在循環中),直到該變量等於taskGroups.Count()

首先考慮使用Task切換到新的異步模式。

無論如何,如果你想等待你所有的線程,你可以調用Thread.Join

var threads = new List<Thread>();    
for (int i = 0; i < taskGroups.Count(); i++) {
    ThreadStart t = delegate { RunThread(taskGroups[i]); };
    var thread = new Thread(t);
    threads.Add(thread);
    thread.Start();
}

threads.ForEach(a => a.Join());

請記住,您還可以傳遞一個超時參數,該參數只有在傳輸時間不超過您傳入的時間后才會等待線程完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM