joe_coolish
joe_coolish

Reputation: 7259

Canceling async httpwebrequests

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!

Upvotes: 3

Views: 7353

Answers (1)

phoog
phoog

Reputation: 43056

From the documentation for HttpWebRequest.Abort():

The Abort method cancels a request to a resource. After a request is canceled, calling the GetResponse, BeginGetResponse, EndGetResponse, GetRequestStream, BeginGetRequestStream, or EndGetRequestStream method causes a WebException with the Status property set to RequestCanceled.

So the behavior you describe is by design. I think you'll have to catch the exception, or else find some way of determining whether Abort was called before calling GetResponse, BeginGetResponse, EndGetResponse, GetRequestStream, BeginGetRequestStream, or EndGetRequestStream.

Upvotes: 4

Related Questions