Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

c# - HttpWebResponse: closing the stream

I'm getting the response from an HttpWebRequest (using a modified version Jeff Richter's CCR wrappers), then inspecting a few of the headers in order to decide whether or not to continue the download. Sometimes I might not want to continue, so I consequently issue response.Close and request.Abort. Is it necessary to issue GetResponseStream then to close the stream, or is this implicit when one calls response.Close?

After issuing GetResponse, the docs state:

You must call the Close method to close the stream and release the connection. Failure to do so may cause your application to run out of connections.

So does this mean that once we have a response, then it is obligatory to get the stream and close it?

We're seeing some fairly strange issues where hung downloads are eventually swamping the system. This seems like the strongest candidate for a resource leak, but wonder if anyone else has experience with this issue.

As an aside: is it safe to GetResponseStream twice in the assumption that it is the same stream?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Calling HttpWebResponse.Close implicity closes the response stream.

From the documentation:

The Close method closes the response stream and releases the connection to the resource for reuse by other requests

You must call either the Stream.Close or the HttpWebResponse.Close method to close the stream and release the connection for reuse. It is not necessary to call both Stream.Close and HttpWebResponse.Close, but doing so does not cause an error. Failure to close the stream can cause your application to run out of connections.

And for your double-GetResponseStream question, although the documentation doesn't explicitly mention it, it will always return the same stream object no matter how many times you call it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...