Multithreading in VB.Net - How to get Main Thread to wait for Worker Threads RRS feed

  • Question

  • I am using VS2008(VB.Net).  My application uses 10 backgroundworker threads to perform optimization work.  The problem I have is that I cannot get my procedure to wait until all 10 Backgroundworkers are finished before it continues.  I have tried several techniques such as ManualResetEvent.WaitOne or AutoResetEvent.WaitAll.  An example of my code is given below.  I get the threads to run no problem, but I cannot get the btnRun.Click eventhandler to wait for all threads to complete before it continues.  As soon as the code reach ManualWaitEvents(0).WaitOne(), no more events fires, and hence Thread1Completed never gets executed. 


    How do I get the main thread to wait until all backgroundworkers finished their work ,before it continues?


    Code Snippet

    Public Class frmOptimise


    Public Thread1 As BackgroundWorker


    Public ManualWaitEvents(0) As ManualResetEvent


    Public Sub New()

    ' This call is required by the Windows Form Designer.



    AddHandler Thread1.DoWork, New DoWorkEventHandler(AddressOf  Thread1Work)

    AddHandler Thread1.RunWorkerCompleted, New RunWorkerCompletedEventHandler(AddressOf Thread1Completed)

    ManualWaitEvents(0) = new ManualResetEvent(False)


    End Sub


    Private Sub btnRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRun.Click





    End Sub


    Private Sub InitialiseData()

    'initialise variables here


    'Start the worker threads



    End Sub


    Public Sub Thread1Work(ByVal Sender As Object, ByVal e As DoWorkEventArgs)


    'code to perform work



    End Sub


    Public Sub Thread1Completed(ByVal Sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)




    End Sub




    Tuesday, March 25, 2008 3:44 AM