Question

Whenever using the WebRequest to test internet connection works fine. However while attemping to connect to internet (after shuting down wifi) and have wifi's status to "no access to internet" IF I do the webrequest again it just doesn't work. I have debugged and found the issue is exactly on line:

objResp = objWebReq.GetResponse

It just takes to long and does not finish.

Below is the function to test the connection:

Dim objUrl As New System.Uri("http://www.google.com")
Dim objWebReq As System.Net.WebRequest
objWebReq = System.Net.WebRequest.Create(objUrl)
Dim objResp As System.Net.WebResponse = Nothing
Try ' Attempt to get response and return True
   objResp = objWebReq.GetResponse
   objResp.Close()
   objWebReq = Nothing
   Return True
 Catch ex As Exception
        objResp = Nothing
        objResp.Close()
        objWebReq = Nothing
        Return False
 End Try

So if user falls in this case (we hope user do not) I was thinking to wait to finish like 5 seconds if it does not finist getting response just stop objWebReq.GetResponse and then return False. But the great question is:

how can I measure time of objWebReq.GetResponse and wait 5 seconds if is taking more than 5 seconds break and return false else return true ?

Était-ce utile?

La solution

You can set your request to timeout after 5 seconds.

See WebRequest.Timeout for full details.

If a timeout happens, an exception will be thrown that you should catch and properly handle.

Descendant classes signal a timeout by throwing a WebException with the Status field set to WebExceptionStatus.Timeout. When Timeout is set to Timeout.Infinite the descendant class does not time out.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top