2

I have a small program that keep posting some data (4MB) to remote server. Each time when an internal 4MB buffer is full, I create a new HttpWebRequest, call BeginGetRequestStream/EndGetRequestStream, write data to stream, close it, and done. Because I don't care about response, so I didn't call GetResponse/BeginGetResponse/EndGetResponse.

My question is, since HttpWebRequest doesn't have a Close method, is it safe to leave current HttpWebRequest instance behind? If I didn't do anything to that HttpWebRequest, will the connection be automatically closed? If answer is no, how to explicitly close current HTTP connection? Thanks.

codewarrior
  • 723
  • 7
  • 22

1 Answers1

1

You shouldn't have to cleanup HttpWebRequest but you do need to close the stream coming back from GetRequestStream or the response from GetResponse. I know you said you aren't using any of the response methods, but you must be using one of them to actually make the request.

After you are finished with a WebResponse object, you must close it by calling the Close method. Alternatively, if you have gotten the response stream from the response object, you can close the stream by calling the Stream.Close method. If you do not close the response or the stream, your application can run out of connections to the server and become unable to process additional requests.[1]

[1] https://msdn.microsoft.com/en-us/library/debx8sh9.aspx

Matt Dearing
  • 9,286
  • 1
  • 23
  • 25