简体   繁体   English

VB.NET AutoResetEvent

[英]VB.NET AutoResetEvent

I am trying to learn more about event handling. 我正在尝试了解有关事件处理的更多信息。 I tried writing the code below but it doesn't seem to be working for some reason. 我尝试在下面编写代码,但由于某种原因似乎无法正常工作。 What I am trying to do is navigating to a url, wait until its loaded and then run the msgbox. 我想做的是导航到一个url,等到它加载后再运行msgbox。

Any idea what I'm doing wrong? 知道我在做什么错吗?

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

You can just catch the DocumentCompleted event on the WebBrowser1 object like this: 您可以像这样在WebBrowser1对象上捕获DocumentCompleted事件:

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

    MsgBox("THe page is loaded")

End Sub

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

When you issue the event_1.WaitOne() , the main thread is blocked. 发出event_1.WaitOne() ,主线程被阻止。 And that includes the WebBrowser. 包括WebBrowser。 Therefore the event_1.Set() will never get executed. 因此, event_1.Set()将永远不会执行。

However, you can achieve the same behavior with a different method. 但是,您可以使用不同的方法来实现相同的行为。 Not using event whatsoever. 不使用事件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM