调用DownloadStringAsync()后获取网页?

时间:2010-04-24 08:25:06

标签: vb.net asynchronous web-crawler

我还不太了解VB.Net还没有使用更丰富的HttpWebRequest类,所以我想我会使用更简单的WebClient类来异步下载网页(以避免冻结UI)。

但是,异步事件处理程序如何实际将网页返回到调用例程?

Imports System.Net

Public Class Form1
    Private Shared Sub DownloadStringCallback2(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
        If e.Cancelled = False AndAlso e.Error Is Nothing Then
            Dim textString As String = CStr(e.Result)

            'HERE : How to return textString to the calling routine?
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim client As WebClient = New WebClient()

        AddHandler client.DownloadStringCompleted, AddressOf DownloadStringCallback2
        Dim uri As Uri = New Uri("http://www.google.com")

        client.DownloadStringAsync(uri)

        'HERE : how to get web page back from callback function?
    End Sub
End Class

谢谢。


编辑:我添加了一个全局共享变量和一个While / DoEvents / EndWhile,但必须有一个更简洁的方法: - /

Public Class Form1
    Shared page As String

    Public Shared Sub AlertStringDownloaded(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
        '  If the string request went as planned and wasn't cancelled:
        If e.Cancelled = False AndAlso e.Error Is Nothing Then
            page = CStr(e.Result)
        End If
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim wc As New WebClient

        AddHandler wc.DownloadStringCompleted, AddressOf AlertStringDownloaded

        page = Nothing
        wc.DownloadStringAsync(New Uri("http://www.google.com"))
        'Better way to wait until page has been filled?
        While page Is Nothing
            Application.DoEvents()
        End While
        RichTextBox1.Text = page
    End Sub
End Class

2 个答案:

答案 0 :(得分:2)

如果使处理函数成为实例方法而不是共享方法,则可以直接在已完成的处理程序中设置RichTextBox1.Text

Public Class Form1

    Private Sub AlertStringDownloaded(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
        '  If the string request went as planned and wasn't cancelled:
        If e.Cancelled = False AndAlso e.Error Is Nothing Then
            RichTextBox1.Text = CStr(e.Result)
        End If
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim wc As New WebClient

        AddHandler wc.DownloadStringCompleted, AddressOf AlertStringDownloaded

        page = Nothing
        wc.DownloadStringAsync(New Uri("http://www.google.com"))
    End Sub
End Class

答案 1 :(得分:1)

你还没找到干净的方法。下载过程中关闭您的表单,看看您将获得的kaboom。您必须至少将表单的Enabled属性设置为False。

查看BackgroundWorker类以干净利落地完成此任务。