Reputation: 408
As WebClient.OpenRead(url) is blocking main thread until it opens url, In my case when server is not responding then it blocks user from activity until it throws timeout exception that's why I need alternative code that should have time out or method that would get data asynchronously.
Here is my code
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
Upvotes: 0
Views: 1175
Reputation: 959
WebClient has an Async version of OpenRead. OpenReadAsync.
Documenation: https://msdn.microsoft.com/en-us/library/system.net.webclient.openreadasync(v=vs.110).aspx
See Yuval's answer for an example: how to wait for webclient OpenReadAsync to complete
Upvotes: 1