user4951
user4951

Reputation: 33138

How to make a thread wait until another thread finish?

Static lock As Object

SyncLock lock
    TraverSingweb.TraverSingWeb.WebInvoke(Sub() TraverSingweb.TraverSingWeb.putHtmlIntoWebBrowser(theenchancedwinclient)) 'This quick function need to finish before we continue
End SyncLock

SyncLock lock
    'SuperGlobal.lockMeFirst(AddressOf SuperGlobal.doNothing) ' donothing
End SyncLock

This is how I currently do in vb.net. Is this a pattern?

Upvotes: 1

Views: 18078

Answers (1)

Randy Dodson
Randy Dodson

Reputation: 252

Here is a really basic example; the main method simply creates two threads and starts them. The first thread waits 10 seconds and then sets the _WaitHandle_FirstThreadDone. The second thread simply waits for the _WaitHandle_FirstThreadDone to be set before continuing. Both threads are started at the same time but the second thread will wait for the first thread to set the _WaitHandle_FirstThreadDone before continuing on.

See: System.Threading.AutoResetEvent for further details.

Module Module1

    Private _WaitHandle_FirstThreadDone As New System.Threading.AutoResetEvent(False)

    Sub Main()
        Console.WriteLine("Main Started")
        Dim t1 As New Threading.Thread(AddressOf Thread1)
        Dim t2 As New Threading.Thread(AddressOf thread2)
        t1.Start()
        t2.Start()
        Console.WriteLine("Main Stopped")
        Console.ReadKey()
    End Sub

    Private Sub Thread1()
        Console.WriteLine("Thread1 Started")
        Threading.Thread.Sleep(10000)
        _WaitHandle_FirstThreadDone.Set()
        Console.WriteLine("Thread1 Stopped")
    End Sub

    Private Sub thread2()
        Console.WriteLine("Thread2 Started")
        _WaitHandle_FirstThreadDone.WaitOne()
        Console.WriteLine("Thread2 Stopped")
    End Sub
End Module

Upvotes: 7

Related Questions