VB.NET:如何使webRequest异步

时间:2011-10-01 19:03:26

标签: vb.net

我认为这对您来说是一个简单的问题,但我不了解其他webRequests案例,所以我在这里问:

如何使此webRequest异步?

Dim sBuffer As String
Dim oRequest As WebRequest = WebRequest.Create(url)
oRequest.Method = "GET"
Dim oResponse As WebResponse = oRequest.GetResponse()
Dim oStream As New StreamReader(oResponse.GetResponseStream())
sBuffer = oStream.ReadToEnd()
oStream.Close()
oResponse.Close()
Return sBuffer

感谢您的帮助!

问候,Flo

1 个答案:

答案 0 :(得分:2)

具有简单返回值的函数不能简单地异步,您需要找到另一种处理返回数据的方法。我建议使用System.Net.WebClient,这是你上面所做的更容易的包装,这个类asynch非常简单。

Dim wc As New WebClient
AddHandler wc.DownloadStringCompleted, AddressOf DownloadCompletedHander
wc.DownloadStringAsync(url)

...

Public Shared Sub DownloadCompletedHander(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
    If e.Cancelled = False AndAlso e.Error Is Nothing Then
        Dim myString As String = CStr(e.Result)
        'Do stuff with data
    End If

End Sub 

我真的不会说VB.net,但我认为这是谷歌搜索