Results 1 to 13 of 13

Thread: Waiting for threaded work method to complete inside a threaded loop

Threaded View

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Mar 2022
    Posts
    83

    Waiting for threaded work method to complete inside a threaded loop

    I am using a threaded loop to spawn a work method, and then wait for the work method to complete before cycling another loop iteration. However, when I specify 4 steps in the loop, I am only getting two steps performed. Is there anything fundamentally wrong in this code? Any better way to do this.

    Code:
    Public AllThreadsDone As New System.Threading.AutoResetEvent(False)
    AllThreadsDone.Set
    
    
    Dim t = New Thread(AddressOf ThreadedLoop)
    t.IsBackground = True
    t.SetApartmentState(ApartmentState.STA)
    threadList.Add(t)
    
    Sub ThreadedLoop()
    
      For j = 0 to 3
        Dim t = New Thread(AddressOf DoWork)
        t.IsBackground = True
        t.SetApartmentState(ApartmentState.STA)
        threadList.Add(t)
    
        Dim t = New Thread(AddressOf waitforthreadcompletion)
        t.IsBackground = True
        t.SetApartmentState(ApartmentState.STA)
        t.Start()
    
        AllThreadsDone.WaitOne()
    
      Next j
    
    End Sub
    
    Sub DoWork()
    
      Thread.Sleep(10000
      WorkThreadDone.Set()
    
    End Sub
    
    Private Sub waitforthreadcompletion()
    
      Try
    retry:
      For Each t In threadList
        If t.IsAlive = True Then GoTo retry
      Next
      AllThreadsDone.Set()
      Exit Sub
      Catch
         GoTo retry
      End Try
    
    End Sub
    Last edited by pel11; Mar 28th, 2022 at 01:19 PM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width