2016-04-15 2 views
0

Поскольку WebClient.OpenRead (url) блокирует основной поток до тех пор, пока он не откроет URL-адрес, в моем случае, когда сервер не отвечает, он блокирует пользователя от активности до тех пор, пока он не выберет исключение таймаута, поэтому мне нужен альтернативный код который должен иметь тайм-аут или метод, который будет получать данные асинхронно.Альтернативный метод для WebClient.OpenRead

Вот мой код

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 

ответ

Смежные вопросы