Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly dispose the stream when using StreamContent

I'm attempting to return a stream from my webapi endpoint, and then clean up by disposing the stream.

I expected this to be the correct way, but the stream is of course disposed before returning.

using(var stream = GetStream()){
    var response = new HttpResponseMessage();
    response.Content = new StreamContent(stream);

    return response;
}

What will be the correct way of disposing the stream?

(Since MSDN says nothing about the behaviour of StreamContent or its methods, my temporary solution is to copy the contents of the stream to a byte array and return that.)

like image 573
Arjan Einbu Avatar asked Aug 05 '16 08:08

Arjan Einbu


1 Answers

As your only resource that needs to be disposed is the Content of the HttpResponseMessage you don't have to worry about it. The framework does the dispose for you. It will dispose the HttpResponseMessage which will do all the disposing needed. Remove the using and it should work just fine.

The HttpResponseMessage will dispose its Content when it is disposed. See .NET Core implementation

The StreamContent will dispose its stream when it is disposed. See .NET Core implementation of StreamContent

If you need to dispose something not disposed by the HttpResponseMessage you may use request.RegisterForDispose as described by Filip Woj

like image 118
Olav Nybø Avatar answered Nov 12 '22 17:11

Olav Nybø