VB.NET AutoResetEvent

时间:2013-04-30 04:17:03

标签: .net vb.net

我正在尝试了解有关事件处理的更多信息。我尝试编写下面的代码,但由于某种原因它似乎没有工作。我想要做的是导航到一个网址,等待它加载,然后运行msgbox。

知道我做错了吗?

Private Shared event_1 As New AutoResetEvent(False)

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    WebBrowser1.Navigate("http://google.com")
    AddHandler WebBrowser1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf wb)

    event_1.WaitOne()

    MsgBox("The page is finished loading ")

End Sub

Private Sub wb(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
    If e.Url.AbsolutePath <> TryCast(sender, WebBrowser).Url.AbsolutePath Then
        Return
    End If
   event_1.Set()
End Sub

2 个答案:

答案 0 :(得分:2)

您可以在WebBrowser1对象上捕获DocumentCompleted事件,如下所示:

Private Sub webBrowser1_DocumentCompleted(ByVal sender As Object, _
    ByVal e As WebBrowserDocumentCompletedEventArgs) _
    Handles webBrowser1.DocumentCompleted

    MsgBox("THe page is loaded")

End Sub

在此处查看示例: http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2

答案 1 :(得分:1)

发出event_1.WaitOne()时,主线程被阻止。这包括WebBrowser。因此,event_1.Set()永远不会被执行。

但是,您可以使用其他方法实现相同的行为。不使用任何事件。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.Enabled = False ' if you realy want to block the UI as well
    WebBrowser1.Navigate("http://www.google.com")

    Do
      Application.DoEvents()
    Loop Until WebBrowser1.ReadyState = WebBrowserReadyState.Complete

    MsgBox("The page is finished loading ")
    Me.Enabled = True ' re-enable the UI
End Sub