0
當程序關閉時,有什麼方法讓ThreadPool完成它的工作?線程池完成工作,當程序關閉時
當我使用一個正常的線程,我只是在t.Join放在FormClosing事件..但ThreadPool似乎沒有任何聯接方法?
當程序關閉時,有什麼方法讓ThreadPool完成它的工作?線程池完成工作,當程序關閉時
當我使用一個正常的線程,我只是在t.Join放在FormClosing事件..但ThreadPool似乎沒有任何聯接方法?
我想我可能已經解決了吧..
Imports System.Threading
Module Module1
Sub Main()
Dim t As New Tool
t.WaitToJoin()
Console.WriteLine("Done")
t.WaitToJoin()
Console.WriteLine("Done")
t.WaitToJoin()
Console.WriteLine("Done")
t.WaitToJoin()
Console.WriteLine("Done")
t.Update()
t.WaitToJoin()
Console.WriteLine("Done")
t.Update()
Thread.Sleep(1500)
t.Update()
t.WaitToJoin()
Console.WriteLine("Done")
t.Update()
Thread.Sleep(1500)
t.Update()
Thread.Sleep(1500)
t.Update()
Thread.Sleep(5500)
t.Update()
Thread.Sleep(10000)
t.Update()
t.WaitToJoin()
Console.WriteLine("Done")
End Sub
End Module
Public Class Tool
'Thread Stuff
Private threads As Integer = 0
Private threadsdone As AutoResetEvent = New AutoResetEvent(False)
Public Sub WaitToJoin()
If Interlocked.Read(threads) > 0 Then
threadsdone.WaitOne(New TimeSpan(0, 0, 30)) ' just to be sure not to lock forever, by some wierd reason, a timeout on 30 sec is added
End If
End Sub
Public Sub Update()
Threading.ThreadPool.QueueUserWorkItem(New Threading.WaitCallback(AddressOf HardWork), "Doing dome hard work...")
End Sub
Public Sub HardWork(ByVal state As Object)
Dim num As Integer = Interlocked.Increment(threads)
Console.WriteLine(num & " - " & state)
Thread.Sleep(10000)
If Interlocked.Decrement(threads) = 0 Then
threadsdone.Set()
End If
End Sub
End Class
以及主要的問題是我需要知道我的所有任務都做了,如1任務可能會持續更長的時間,然後另一個..如果我只跟蹤最後一項任務,我可能會監督其中一個需要更長的時間 – Droa