WebClient.OpenRead

时间:2016-04-15 14:16:11

标签: c# vb.net

由于WebClient.OpenRead(url)阻止主线程直到它打开url,在我的情况下,当服务器没有响应时,它阻止用户从活动,直到它抛出超时异常,这就是为什么我需要替代代码应该有时间或将以异步方式获取数据的方法。

这是我的代码

Public Function IsUpdateAvailable(ByVal isAutoUpdate As Boolean) As String
        Dim client As WebClient

        Try
            Dim configUrl As String = GetURL()
            Dim configFile As String = GetFileName()

            If String.IsNullOrEmpty(configUrl) Then
                If Not isAutoUpdate Then
                   Return "Unable to check for updates" 
                End If
            End If

            If String.IsNullOrEmpty(configFile) Then

                If Not isAutoUpdate Then
                    Return "Unable to check for updates" 
                End If

            End If

            configUrl = configUrl & configFile

            If Not configUrl.ToUpper.StartsWith("HTTP") Then
                configUrl = "http://" & configUrl
            End If
            client = New WebClient
            Dim gfStream As Stream = client.OpenRead(configUrl)
            Dim gfStreamReader As New StreamReader(gfStream)
            Dim line As String = String.Empty
            Dim version As String = String.Empty
            Dim stringList As New Collections.Generic.List(Of String)

            While Not gfStreamReader.EndOfStream
                line = gfStreamReader.ReadLine
                If Not String.IsNullOrEmpty(line) Then
                    stringList.Add(line)
                End If
            End While
            gfStreamReader.Close()
            gfStream.Close()

            If stringList.Count > 0 Then
                version = stringList(0)
                If stringList.Count > 1 Then
                    _downloadFilePath = stringList(1)
                End If
                If isGreaterVersion(version) Then
                    Return "True"
                Else
                    If Not isAutoUpdate Then
                        Return "Current version is up-to-date."
                    End If

                End If
            Else
                If Not isAutoUpdate Then
                   Return "Current version is up-to-date."
                End If
               Return False
            End If
        Catch ex As WebException
            Return "Unable to check for updates" 
        Catch ex As Exception
            Return "Unable to check for updates" ''
        End Try

    End Function

1 个答案:

答案 0 :(得分:1)

WebClient具有OpenRead的异步版本。 OpenReadAsync。

文件:https://msdn.microsoft.com/en-us/library/system.net.webclient.openreadasync(v=vs.110).aspx

请参阅Yuval的答案,例如:how to wait for webclient OpenReadAsync to complete