如何使线程等到另一个线程完成?

时间:2012-05-01 06:23:16

标签: vb.net multithreading

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

这就是我目前在vb.net中的表现。这是一种模式吗?

1 个答案:

答案 0 :(得分:7)

这是一个非常基本的例子; main方法只创建两个线程并启动它们。第一个线程等待10秒,然后设置 _WaitHandle_FirstThreadDone 。第二个线程只是等待 _WaitHandle_FirstThreadDone 在继续之前设置。两个线程同时启动,但第二个线程将等待第一个线程设置 _WaitHandle_FirstThreadDone ,然后继续。

有关详细信息,请参阅:System.Threading.AutoResetEvent

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