How to dispose HttpResponseMessage.Content without closing Stream ?
Hi,
it looks like the HttpRequestMessage Problem (a using around "new HttpRequestMessage()" also disposing a Stream given as method parameter) was fixed in .NET Core 2.0. @stephentoub wrote about it here: https://github.com/dotnet/corefx/pull/19082
But this problem still exists with HttpResponseMessage. Here is some example Code:
public async Task<Stream> DownloadFile(string url)
{
using (var request = new HttpRequestMessage(HttpMethod.Get, url))
{
using (var response = await httpClient.SendAsync(request))
{
// Handle errors here
// Do stuff with headers, media type etc.
return await response.Content.ReadAsStreamAsync();
}
}
}
This is code in a library. Problem here is, we do not wanna completely download stuff here, in example into a MemoryStream. We just want to give back the Stream, so users can decide how and when to handle it and when to really start reading the data.
But the problem here is, that the using of the HttpResponseMessage ("using (var response = ...") calling Dispose() of the HttpResponseMessage, and this calls the Dispose() of the response.Content, and this dispose and close the stream.
The stream we give back is already closed when the method ends. So we tried to figure out whats to do here. And we found no solution, besides derive a own class from Stream and set in this class everything else what is to dispose (like our HttpContent here), since the user is responsible for disposing Stream (it implements IDisposable, so he have to apply the Dispose Pattern to the resulting Stream of our method) and when the user Dispose() our Stream it also disposes the HttpContext. Something along the lines what openstack did (they called it DelegatingStream) or in some direction stuff in old ASP.NET MVC WebApi did with "RegisterForDispose()".
We looked also at the source code of HttpContext.Dispose() to find out if we just can ignore the Dispose(), because maybe it only disposes the Stream when being a StreamContext. But since there is also code for Buffering in there (that disposes a MemoryStream), we are not sure if it is good to ignore Dispose() here.
Any help or change or idea is very very appreciated ! Maybe someone can tell us, how this design is build in mind and how we should use it ?
Maybe this issue is also somewhat of the same direction: https://github.com/dotnet/corefx/issues/1794
In general, the objects inside the HttpResponseMessage are owned by the HttpResponseMessage. So, disposing the HttpResponseMessage disposes everything inside it including the .Content object (HttpContent) which owns the underlying content which is the HTTP response stream.
Changing this behavior would probably require a new API to control this behavior.
@stephentoub @geoffkizer @Tratcher
Any help or change or idea is very very appreciated
Just don't dispose the response? The resources will be cleaned up when the stream is disposed.
Yeah, the stream is the only thing on the response that really needs disposing, so if you're not ready to dispose it then don't.
Hi,
sorry that i respond a bit late, but i am somewhat ill at the moment.
First, thx for the comments.
But my question stays the same. This is the Dispose() method of HttpContext:
protected virtual void Dispose(bool disposing)
{
if (!disposing || this._disposed)
return;
this._disposed = true;
if (this._contentReadStream != null)
{
(this._contentReadStream as Stream ?? (!(this._contentReadStream is Task<Stream> contentReadStream) || contentReadStream.Status != TaskStatus.RanToCompletion ? (Stream) null : contentReadStream.Result))?.Dispose();
this._contentReadStream = (object) null;
}
if (!this.IsBuffered)
return;
this._bufferedContent.Dispose();
}
So, whats about „this._bufferedContent.Dispose() and the according MemoryStream, when i „just do not call Dispose() of HttpContext ?
Besides that: This can not be a good design, to just say or expect, that the user of a Library have to know when NOT to call Dispose(). From the outside a user just see HttpContext implements IDisposable and so he have to dispose. Thats it.
Or in other words: HttpContext never should Dispose its result aka the Stream, because also Stream implements IDisposable and the user therefore knows that he have responsibility for it and that he have to dispose. So, why the HttpContext dispose the stream in the first place ? Makes no sense for me or i do not understand the stuff behind that descission.
Any help or change or idea is very very appreciated
Just don't dispose the response? The resources will be cleaned up when the stream is disposed.
Hi Stephen, thx for your quick answer. But how do „the stream“ cleans (by calling Dispose()) up the HttpContext ? When i not dispose the HttpContext (so that the stream keeps open) and after a while dispose the Stream, the Stream itself doesnt call Dispose() of HttpContext or does he ? Sorry, i do not get what you mean.
I'm not sure what HttpContext is here in this discussion. Do you mean HttpResponseMessage and HttpContent? If so, it's disposable mainly to dispose of the stream. If you have access to the stream, then you can just dispose it, and it appropriately cleans up after the whole operation, returning the connection to the connection pool, etc. It won't end up calling HttpContent.Dispose, but that would only matter if you had some custom HttpContent-derived type that did something custom in its Dispose method beyond disposing of the response stream.
Hi everyone,
I recently discussed this issue with @MBODM and wanted to provide my two cents to the discussion. Ignoring Dispose() may be possible at this point in time, because the implementation in HttpContent in .net core only disposes of its underlying Stream for which we can safely pass on the responsibility by returning it from our DownloadFile(File) method.
This assumption would be "fine" as long as we had control of HttpContent's code, which we do not have. For this library we depend on netstandard2.0. Thus, any difference between netstandard implementations of HttpContent breaks this assumption. Any future change to HttpContent's implementation that adds another IDisposable resource breaks this assumption. Do we not have to dispose of HttpContent, and HttpResponse for that matter, in order to be safe on any platform, now and in the future?
Ah, thx @asdorius, i forgot to mention that too.
Besides that, @stephentoub, i am still not convinced: At the moment no one answered my above question about this code in HttpContent.cs (.NET Core implementation) here:
if (!this.IsBuffered)
return;
this._bufferedContent.Dispose();
When is stuff buffered here and when not ? Because: WHEN stuff is buffered, a MemoryStream is in use (inside HttpContent.cs) that no one ever will dispose, if Dispose() of HttpContent is just ignored as you mentioned, instead called by us.
PS: Sorry for the confusion above with HttpContent and HttpContext. I did a lot ASP stuff lately, so my mind sometimes confuse the both :) Sorry!
Since it's more than 2 weeks now, but at least the issue is still open, i just carefully may ask:
Any answers ? Nobody ?
:)
I am just not sure, if it is really safe here, to not dispose the HttpContent. For the reason i asked above (and no one answered), as well as for the reason @asdorius mentioned in second part of his answer (which i also agree too).
The model is that you need to dispose of the response content or stream; you can but do not need to dispose of both. The handler that creates the response content and stream is responsible for ensuring resources are appropriately cleaned up according to that contract.
Thx Stephen for your time! I am sure as hell, a Stephen Toub has stuff to get done, that is way more worth his time, than this shit :) So, thx for the comments.
That said, the answer is very disappointing. Because wether this answers which one will dispose that MemoryStream above, that is used inside HttpClient and which is disposed in the Dispose() method of the HttpContent (which no one will ever call -> your advice in your answer), nor it takes account for the fact that @asdorius mentioned. And as he said, it is very bad design in the first place. Also i asked that MemoryStream question already 2 times, but no one cares. Obviously it does not matter if that MemoryStream is disposed or not !?! Hopefully... !?!
So, i assume that‘s it. Take it or leave it.
Personally i had the hope that Microsofts new „open source community route“ would offer more gain in the end of the day... but it seems i have to accept that i do not get answers here, so i do something i am not in control of and do not know what will happen in the worst case sceanrio and deliver risky software or i choose another way, by work out a complex solution that guarantees disposing of HttpContent or choose another technology than .NET Core here. Left with that options while still have no accurate answers for our companies questions is not what i hoped to find here. But that‘s life.
Sorry for being a bit salty here. We just wanna do that stuff right. But this is not the end of the world :)
So i just can say at this point: Thank you for trying to shed some light into this, nontheless!
I'm sorry you don't like the answer. I'm not sure how it could be better.
A few statements that have already been made:
- MemoryStream.Dispose is currently a nop.
- it's the responsibility of the handler/HttpClient creating the response to ensure the resource cleanup model is reliable.
That means that you can Dispose either or both the response and/or stream, and you're covered. If the memory stream implementation were to change such that Dispose became important, HttpClient/SocketsHttpHandler would change as well. They're all part of the framework implementation, version together, etc.
Thx Stephen for this additional infos!
I didn´t know this fact about MemoryStream. Also can not see above where this was mentioned? But: Thx for this information! This is a first step in the right direction, because if i really do not have to care about the disposing of the underlying MemoryStream in HttpContent.cs (used for that buffering mentioned above) in the .NET Core source, because Dispose() of MemoryStream is a nop code, well, then i will sleep a bit better :) Didn´t know that.
Statement of @asdorius is still true. And i am still convinced that HttpContext should be aware of disposing his OWN stuff, but NEVER the resulting stream, since that result implements IDisposable and goes into the hands of the user of that framework method and therefore it is in his responsibility, to Dispose() that resulting stream, after he finished using it. It is the user´s responsibility, not the responsibility of the framework.
I do not really understand your last statement, since it sounds like you missunderstood us and what our goals or problems are. Because i EXACTLY CAN NOT dispose the response, because this leads to the disposing of the resulting stream, by .NET Core source code. Or in short: You can not return that resulting stream (from .NET Core), in some method A() (in example), so a user of method A() could work with the resulting stream (and finally dispose it), when you also dispose the response in a using clause inside that method A(). Because response.Dispose() leads (inside .NET Core) to resultingStream.Dispose() and this closes that stream. So the user of our method A() will get a closed stream, when method A() returns.
But the info that MemoryStream.Dispose() is useless and could be safely ignored (at the moment!) helps us! And as you stated, if that changes, hopefully this code above is also changed. And when (if ever) MemoryStream.Dispose() becomes an important non-NOP thing, we have to call, hopefully we realize that MemoryStream changed, without having thousands of dangerous un-disposed MemoryStream instances out there, after updating the framework :) Because we use above problematics in thousands of parallelized spawned client/server communication instances. But these are just some paranoid thoughts out of my mind :) In the end, nobody really can plan the future. And i assume MemoryStream wasn´t changed since a decade or so :) So, who cares ? :)
I think the sky isn´t falling, by ignoring the dispose pattern here. So i think this is a acceptable solution for us at the moment.
So thx a lot and best wishes to you, Stephen!