I have stream, that comes from a ReadAsStreamSync() method from an HttpContent object. I'm returning this stream from a method, so the caller of my method can read directly from the http stream, without having to buffer the entire response in memory.
The issue I now have, is that I need to know when the stream I return is disposed. Since there is no "disposed" event on a stream, I'm thinking I can wrap the stream in a class that inherits memorystream, and override the dispose method. However, I don't want to copy the ENTIRE response stream to the memorystream, because this would mean the entire content would be written to memory. I think this is possible, but I can't seem to find any info about it.
Is there anyone who can help me with this? Or provide me with an alternative method to be able to tell when a stream is being disposed.
Edit:
After reading the comments it seems that I haven't been very clear. Let me give you a concrete example:
public class StreamGetter()
{
public Stream GetSomeStream()
{
//some code here that gets the stream
//and return the stream, this stream might be 100mb long,
//and since this method doesn't know what to do with it,
//we return the stream so the calling method can figure it out
return generatedStream;
}
}
public void SomeOtherMethod()
{
using(var stream = GetSomeStream())
{
//some some stuff
}
}
Now the thing is, the stream that is fetched is a stream that comes from a ReadAsStreamAsync() of the content of an httpResponseMessage, which is fetched using an HttpClient. Now I need to dispose the HttpClient once the stream is disposed. If I dispose it earlier, I can no longer read from the stream. If I don't dispose it, the resources are never freed.
Now before anyone starts mentioning i shouldn't dispose HttpClient because it is made for re-usage. I know about it, and I don't reuse HttpClient, but the underlying HttpClientHandler.
If you think my design is a bad design, I'm also open to suggestions on how to write the code differently. The only requirement is that I keep all code related to the HttpClient in the "StreamGetter" class, and all handling of the result stream outside of the "StreamGetter" class.
edit2: I think I found a solution by changing the class. By making the StreamGetter class implement idisposable, I can move the responsibility to dispose stuff outside of the StreamGetter class. The calling class can now create a using block, call the "GetSomeStream" method, and process the results all within the using block. The dispose method of the StreamGetter then disposes the HttpClient. Any thoughts on this?