2014-09-23 86 views
0

我有一個簡單的按鈕,發送獲取請求來檢索我的網站上的TXT文件。問題是它凍結了應用程序,同時檢索信息。我怎樣才能使它在等待結果時不凍結?如何等待獲取請求,而不凍結客戶端

Private Sub cmd_ClickMe_Click(sender As Object, e As EventArgs) Handles cmd_ClickMe.Click 
    Dim request As String = String.Format("http://www.*****/database/test.txt") 
    Dim webClient As New System.Net.WebClient 
    Dim result As String = webClient.DownloadString(request) 

    MessageBox.Show(result) 
End Sub 

我也試過以下,但它不工作(稱 「webClient.DownloadStringAsync(myUri)」 不會產生一個值:

Private Sub cmd_ClickMe_Click_1(sender As Object, e As EventArgs) Handles cmd_ClickMe.Click 
    Dim request As String = String.Format("http://www.****.com/database/test.txt") 
    Dim webClient As New System.Net.WebClient 
    Dim myUri As Uri = New Uri(request) 

    Dim result As String = webClient.DownloadStringAsync(myUri) 

    MessageBox.Show(result) 
End Sub 
+0

您想將其卸載到單獨的線程以防止UI在處理期間變得無響應。這裏有一些信息這樣做,http://msdn.microsoft.com/en-us/library/aa719109(v=vs.71).aspx – Lbatson 2014-09-23 16:58:30

回答

3

使用DownloadStringAsync(Uri)而不是DownloadString(uri)

DownloadStringAsync方法不會阻止調用線程

下面是一個例子,如何使用它:

Dim wc As New WebClient 
    ' Specify that you get alerted 
    ' when the download completes. 
    AddHandler wc.DownloadStringCompleted, AddressOf AlertStringDownloaded 

    Dim uri As New Uri("http:\\changeMe.com") 'Pass the URL to here. This is just an example 
    wc.DownloadStringAsync(uri) 

End Sub 

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 

     Dim myString As String = CStr(e.Result) 'Use e.Result to get the String 
     MessageBox.Show(myString) 
    End If 

End Sub 
+0

與此我得到以下錯誤:「類型的值字符串'不能轉換爲'System.Uri'「 – dlofrodloh 2014-09-23 17:16:00

+0

如果你傳遞一個字符串而不是一個合理的錯誤信息的uri對象。從你的字符串創建一個uri對象:Dim myUri As Uri = New Uri(request)並將其傳遞給異步方法。 – Postlagerkarte 2014-09-23 17:27:54

+0

我已經添加了,但我得到的錯誤:「表達式不會產生一個值」。我在上面的問題中添加了該代碼 – dlofrodloh 2014-09-23 17:48:07

相關問題