线程池完成工作,当程序关闭时



有没有办法让线程池在程序关闭时完成它的工作?

当我使用普通的线程时,我只是在 FormClosing 事件上输入了 t.Join..但 ThreadPool 似乎没有任何 Join 方法?

我不认为你可以让线程池等待。使用任务而不是线程池怎么样?大意如下的代码。您可以在此处查看完整示例以更好地理解

    Dim taskA = Task.Factory.StartNew(Sub() DoSomeWork(10000000))
    taskA.Wait()
    Console.WriteLine("taskA has completed.")

我想我可能已经解决了它。

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

相关内容

  • 没有找到相关文章

最新更新