我不知道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
感謝您提供關於「公共共享」與私人共享的提示。 – Gulbahar 2010-04-27 17:55:42