3

Are streams disposed in NancyFx when using StreamResponse()?

Using a streamWriter to write to the stream, I can't dispose of it without closing the stream I want to send out. And the way I see it, I can't dispose of the stream manually either since I effectively left the method at the return.

This code works:

// Open a stream and write to it with streamReader
Stream memStream = new MemoryStream();
StreamWriter memWriter = new StreamWriter(memStream, Encoding.UTF8);
memWriter.Write(someStringText);
memWriter.Flush();
memStream.Position = 0;

// Add stream to the respose which should get downloaded
var response = new StreamResponse(() => memStream, MimeTypes.GetMimeType(contentType));
return response.AsAttachment(someFileName);

Do I need to worry about the stream lingering on until the garbage collector comes along or do it get disposed correctly by the StreamResponse?

Bingla
  • 447
  • 4
  • 17
  • If that class implement IDisposable, then dispose it, if you are finish with it. –  Aug 09 '16 at 12:46

1 Answers1

2

According to StreamResponse.cs, StreamResponse.Dispose() disposes of the stream returned by the Func<Stream>, and Nancy handles disposing the Response at the end of the NancyContext.

As for disposing of StreamWriter without affecting the underlying stream, see this answer.

MrZander
  • 3,031
  • 1
  • 26
  • 50
Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
  • And the streamWriter can safely be managed by the garbage collector? I see no way to handle that without closing the stream. – Bingla Aug 09 '16 at 13:07
  • When is StreamResponse.Dispose() called though? Is that handled by Nancy, or do we need to call it explicitly? – Mac Sep 14 '16 at 01:07