views:

438

answers:

2

Are there any known issues with canceling HttpWebRequest HTTP requests? We find that when we cancel 4-5 requests, the next request hangs indefinitely.

If there are no known problems with this, then I'm probably doing something wrong... where is a good resource example that shows how this works (a complete solution, not a couple of code snippets)?

If there are known problems, what can I do to work around them, in order to effectively cancel as many requests as I need to?

+1  A: 

After you cancel the request, take care to close the response stream, otherwise you will have leaks.

I usually use "using" when obtain the response from the web request to ensure that the response is closed:

WebRequest request = WebRequest.Create("http://google.com");

using (WebResponse response = request.GetResponse())
{
   //do my job
}

That way, even if you cancel the request, or it throws an exception during response reading, the resposne and it's stream will be closed.

Sunny
A: 

When I try to cancel upload it keeps breaking not allowing me to make another upload. What should I do? HELP please!

using (Stream requestStream = webrequest.GetRequestStream())
{    
while (chunksToWrite)
{
  requestStream.Write(chunk++);

  if (worker.CancellationPending)//or other cancel method
  {
    webrequest.Abort();
    requestStream.Close();
   }
}
}