2012-01-23 48 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但是太复杂了 –