2010-04-24 67 views
1

我不知道VB.Net還沒有使用更豐富的HttpWebRequest類,所以我想我會使用更簡單的WebClient類異步下載網頁(以避免凍結UI)。在調用DownloadStringAsync()之後獲取網頁?

但是,異步事件處理程序如何將網頁實際返回到調用例程?

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 

謝謝。


編輯:我添加了一個全球性的共享變量和在/的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

如果您使處理函數成爲實例方法而不是共享,則可以直接在完成的處理程序中設置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 
+0

感謝您提供關於「公共共享」與私人共享的提示。 – Gulbahar 2010-04-27 17:55:42

1

你有沒有發現一個乾淨的方式。在下載過程中關閉你的表單,看看你會得到的kaboom。您必須至少將窗體的Enabled屬性設置爲False。

看看BackgroundWorker類,乾淨地做到這一點。

+0

我想在應用程序忙於下載文件時顯示錶單。我會嘗試禁用它,然後看看它是如何發生的。謝謝。 – Gulbahar 2010-04-27 17:55:18