1

Is there any method of stopping the code running while the HttpWebResponse is still loading the progress?

For example I'm running this code and I'm sure it'll take 10 seconds to get the response:

Dim urlAddress As String = "https://google.com"
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(urlAddress), HttpWebRequest)
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)

And now, while the request is getting response... as example at the second 4 I will press the stop button which will abort getting the response and it'll popup a MessageBox.

 Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn.Click
       HttpWebResponseName.Abort()
       MessageBox.Show("Done!")
End Sub

Thank you!

Mava
  • 73
  • 10

1 Answers1

0

It looks like this code is intended to run client side. Remember, from the client perspective, you send a Request, and Receive a response. The response comes from the server, so you cannot control it. Instead, you can abort the request that results in the response (so you'll need to keep a hook to that request in order to Abort it):

Private _activeRequest As HttpWebRequest
'...  other member-level code here

Then, your code that creates the request can be updated to:

Dim urlAddress As String = "https://google.com"
_activeRequest =  DirectCast(WebRequest.Create(urlAddress), HttpWebRequest)
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)

Which will make your click event method look like this:

Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn.Click
    _activeRequest.Abort()
    MessageBox.Show("Done!")
End Sub
Ed Mooers
  • 26
  • 4
  • I've tried this already, but the HttpWebResponse will still wait till it'll actually get a response or the timeout will be reached, so the code will still run even with the request aborted. So this doesn't help that much, I'm trying to stop anything that has to do with the response & request at the same time, then do other things. – Mava Jun 27 '17 at 10:34