0

Is there a way to make a ThreadPool finish its work, when the Program is closing?

when i was using a normal Thread, i just putted in t.Join on the FormClosing event.. but ThreadPool seems not not have any Join methode?

Droa
  • 427
  • 7
  • 15

2 Answers2

1

I dont think you can make a Threadpool wait. How about using a Task instead of threadpool? Something to the effect as following code. You can check the complete example here for a better understanding

    Dim taskA = Task.Factory.StartNew(Sub() DoSomeWork(10000000))
    taskA.Wait()
    Console.WriteLine("taskA has completed.")
samar
  • 5,021
  • 9
  • 47
  • 71
  • well main problem is i need to know when ALL my tasks are done, as 1 task could last longer then another.. if i only keep track of the last task, i might oversee one of the one taking longer – Droa Oct 09 '13 at 12:37
0

i think i might have solved it..

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
Droa
  • 427
  • 7
  • 15