Should I close the HttpRequest input stream that my code has never accessed?
I have some old code running in ASP.NET that works something like this:
void HandleRequest(HttpContext context)
{
try {
if( some condition ) {
try {
doSomething( context.Request.InputStream );
} finally {
context.Request.InputStream.Close();
}
}
// moar code follows which doesn't access InputStream
} finally {
context.Request.InputStream.Close();
}
}
Note that regardless of whether or not accessed InputStream
, it is retrieved and closed. I think this is a waste of time and the second is .Close()
redundant.
Do I need to close the HttpRequest input stream that my code has never accessed?
source to share
Since you are not creating InputStream
, you should not be held responsible for closing it down.
Rules like this should keep us sane - if you're responsible for shutting it down, what other objects are you responsible for? HttpContext
has many properties to check. And what happens to the existing code if they add a new property to HttpContext
?
If they want you to feel responsible for closing it, it should be public Stream CreateInputStream()
instead, and definitely not a property.
source to share
Not. It will be removed by HttpRuntime, which calls HttpContext.Request.Dispose after the request completes. Check out the source code here. http://referencesource.microsoft.com/#System.Web/xsp/system/Web/HttpRuntime.cs#c0635347fb5a9826 http://referencesource.microsoft.com/#System.Web/xsp/system/Web/HttpRequest.cs # 118b5aa7679e37f7
source to share