2012-01-23 49 views
0

任何人都知道這麼做的簡單方法?如何等待,直到線程池中的所有工作線程都消失

基本上,我排隊所有的作品後,我想等待,直到我所有排隊完成。我該怎麼做?

loopThroughAllBlog(whattodo, login)'queue all works 

//在這裏做什麼等待所有排隊的作品完成。

Dim whatToWrite = New Generic.List(Of String) 
    For Each domain In domainsSorted 
     whatToWrite.Add(dictionaryOfOutput.Item(domain)) 
    Next 
    coltofile(whatToWrite, "output.txt", True) 

我注意到沒有辦法知道有多少線程仍在線程池中運行。

+0

您是否在尋找線程連接?從調用進程(或線程)開始,您應該先等待線程加入,然後再繼續。 – Shredderroy

+0

我可以做線程連接,但我怎麼知道線程池中的線程? –

+0

希望這應該讓你開始:http://msdn.microsoft.com/en-us/library/3dasc8as(v=vs.80).aspx – VS1

回答

0

我最終回答了我自己的問題,因爲沒有答案。

Public Function threadPoolIdle() As Boolean 
    Dim workerThreads As Integer 
    Dim completionPorts As Integer 
    Dim maxWorkerThreads As Integer 
    Dim maxCompletionPorts As Integer 
    Dim stillWorking As Integer 

    Threading.ThreadPool.GetAvailableThreads(workerThreads, completionPorts) 
    Threading.ThreadPool.GetMaxThreads(maxWorkerThreads, maxCompletionPorts) 
    stillWorking = maxWorkerThreads + maxCompletionPorts - workerThreads - completionPorts 

    If stillWorking > 0 Then 
     Return False 
    Else 
     Return True 
    End If 

End Function 

Public Sub waitTillThreadPoolisIdle() 
    Do 
     Sleep(1000) 
     Application.DoEvents() 
    Loop While threadPoolIdle() = False 
End Sub 

我認爲這只是尷尬。一定有更好的方法。

+0

男孩我寫作品的答案。那麼這是我實際使用的:) –

4

實現此目的的常用方法是使用受信號量保護的計數器。 (在我看來,你的代碼是VB,我不知道VB,所以我的語法可能是關閉的,把它當作僞代碼)。

首先,你需要設置信號燈和計數器:

' a semaphore is a counter, you decrease it with WaitOne() and increase with Release() 
' if the value is 0, the thread is blocked until someone calls Release() 
Dim lock = new Semaphore(0, 1) 
Dim threadcount = 10 ' or whatever 

在函數的末尾由線程池運行,你需要減少線程計數器,並釋放鎖如果THREADCOUNT在0

threadcount = threadcount - 1 
if threadcount = 0 then 
    lock.Release() 
end if 

等待你的線程時,嘗試將收購的信號,這將阻塞,直到有人叫釋:

lock.WaitOne() 

對於上面的減少和檢查操作,你可能想要把它放在一個單獨的子程序中。您還需要保護它,以便每個嘗試訪問計數器的線程都與其他線程隔離。

dim counterMutex = new Mutex() 
sub decreaseThreadCount() 
    counterMutex.WaitOne() 
    threadcount = threadcount - 1 
    if threadcount = 0 then 
     lock.Release() 
    end if 
    counterMutex.release() 
end sub 
+1

我看到Vijay提供的鏈接使用WaitHandle,這似乎是一個更高層次的方法來實現相同。我的答案是使用信號量進行同步的文本示例,WaitHandle似乎是相同原理的更高級別的應用程序。 –

+0

如果你想在你的主線程上得到通知(就像你似乎做的那樣),最後一個線程(將線程安全計數器遞減爲0的線程)更常見,調用/ BeginInvoke信號/消息到主線程,因此在線程/線程池活動期間不會阻塞它。 –

+0

+1但是太複雜了 –