I'm trying to get an HttpWebResponse
object asynchronously, so that I can allow the request to be cancelled (using the BackgroundWorker.CancellationPending
flag). However, the request.BeginGetResponse
line below blocks until a response is returned (and this can take longer than a minute).
Public Function myGetResponse(ByVal request As HttpWebRequest, ByRef caller As System.ComponentModel.BackgroundWorker) As HttpWebResponse
'set a flag so that we can wait until our async getresponse finishes
Dim waitFlag = New ManualResetEvent(False)
Dim recieveException As Exception = Nothing
Dim response As HttpWebResponse = Nothing
'I use beginGetResponse here and then wait for the result, rather than just using getResponse
'so that this can be aborted cleanly.
request.BeginGetResponse(Sub(result As IAsyncResult)
Try 'catch all exceptions here, so they can be raised on the outer thread
response = request.EndGetResponse(result)
Catch e As Exception
recieveException = e
End Try
waitFlag.Set()
End Sub, Nothing)
While Not waitFlag.WaitOne(100) AndAlso Not caller.CancellationPending
'check for cancelation every 100ms
End While
'if our async read from the server returned an exception, raise it here.
If recieveException IsNot Nothing Then
Throw recieveException
End If
Return response
End Function
The MSDN documentation for BeginGetResponse
includes the paragraph,
The BeginGetResponse method requires some synchronous setup tasks to complete (DNS resolution, proxy detection, and TCP socket connection, for example) before this method becomes asynchronous. As a result, this method should never be called on a user interface (UI) thread because it might take some time, typically several seconds. In some environments where the webproxy scripts are not configured properly, this can take 60 seconds or more. The default value for the downloadTime attribute on the config file element is one minute which accounts for most of the potential time delay.
Am I doing something wrong, or is it likely these initial synchronous tasks that are causing the delay? If the latter, how do I make this call actually asynchronous?
This answer seems to suggest a possible .NET bug, but I know the URL I'm using is valid (I'm running a dev server locally)
I'm using VS 2010 and .NET 4.0