0

I use HttpWebResponse.BeginGetResponse() method to make a request to my server. In the "Request Complete" notification I do the following (no error handling code included):

HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(result);
BinaryReader streamReader = new BinaryReader(response.GetResponseStream());

while ((readSize = streamReader.Read(buffer, 0, buffer.Length)) > 0)
{
...
}

My question is if it is OK to store the Stream obtained from response.GetResponseStream() somewhere as a member variable and make the Cancel of the request like this:

m_requestState.httpRequest.Abort();
m_requestState.httpRequestStream.Close(); // If this is missing then
// streamReader.Read() locks for a long time when connection is lost.

This code causes the streamReader.Read() to throw System.ObjectDisposedException.

Thank you!
Mihai

Mihai
  • 89
  • 6

2 Answers2

1

it's best if you store your webRequest instead and cancel it in a try catch:

    public void Cancel()
    {
        IsCancelled = true; 

        try
        {
            if (WebRequest != null)
            {
                WebRequest.Abort();
            }
        }
        catch (Exception ex)
        {
            // slicence!
        }
    } 

See WebDownloader HelperClass here:

http://www.manorey.net/mohblog/?p=17#content

IsCancelled flag is set in the cancel() method to avoid calling OnComplete() even after the Abort() is called.

Mo Valipour
  • 13,286
  • 12
  • 61
  • 87
  • Hi Valipour! I have a flag similar to IsCancelled but this is not enough because the cancel request I want to perform is inside the "Request Complete" notification while I am reading the data from the stream. Note that I am using myHttpWebRequest.AllowReadStreamBuffering = false so that not all the data is available locally when the "Request Complete" is called. Without calling the m_requestState.httpRequestStream.Close() the application locks into the streamReader.Read() call because no more data can be read from the broken connection. – Mihai Jul 14 '11 at 06:54
  • I'm also saving the web request as m_requestState.httpRequest and I call Abort in the Cancel function: 'm_requestState.httpRequest.Abort();' – Mihai Jul 14 '11 at 07:04
1

After I did some research, my conclusion is that the only solution to unlock streamReader.Read() is to include in the canceling method also the call tom_requestState.httpRequestStream.Close() (as stated in the initial question). This will make the call streamReader.Read() to throw ObjectDisposedException exception and the "Request Complete" notification to finish execution.

axel22
  • 32,045
  • 9
  • 125
  • 137
Mihai
  • 89
  • 6