I am making an app that will make several HttpWebRequest objects and downloading my html via the httpRequest.BeginGetResponse
method. I get back the IAsyncResult
and store it locally so that I can cancel the request at any time, but I'm not sure if I'm doing that correctly.
Here is what I'm doing to cancel the async web request:
var res = (RequestState)asyncResult.AsyncState;
res.Request.Abort();
Where Request is of type HttpWebRequest
.
What I'm noticing is that even after I call these lines of code, I still have all of the Async threads open in my application. And if I set a break point in the delegate called in httpRequest.BeginGetResponse(GetResponseCallback, state)
(e.g. the method GetResponseCallback
) The debugger breaks inside the method after a few seconds, causing a WebException to be thrown when that method is ran.
Just for completeness, my GetResponseCallback looks like this:
using (var httpWebResponse = (HttpWebResponse)request.EndGetResponse(result))
using (Stream dataStream = httpWebResponse.GetResponseStream())
using (var reader = new StreamReader(dataStream))
{
string ret = reader.ReadToEnd();
state.OnComplete(ret, new EventArgs());
}
and I get the WebException on the using (Stream dataStream = httpWebResponse.GetResponseStream())
line. The inner exception says something like "the server actively refused the connection" or something like that.
Any help would be excellent!