Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing streams, always necessary? .net

Tags:

c#

stream

Is it always necessary to close streams or, because .net is managed code, will it be closed automatically as soon as it drops out of scope (assuming there are no exceptions raised).

Illustrated:

static string SerialiseObjectToBase64(object obj)
{
    var mstream = new MemoryStream();
    ...
    return Convert.ToBase64String(mstream.ToArray());        
}

Is the above code acceptable?

like image 957
maxp Avatar asked Mar 01 '10 22:03

maxp


People also ask

Why should you always close streams?

If you don't close streams, you may have problems opening them back up again. This is especially true if they're hanging off the end of sockets. Closing a stream also makes sure that data is flushed through the stream if there is any data left to send.

Do I need to close MemoryStream?

You needn't call either Close or Dispose . MemoryStream doesn't hold any unmanaged resources, so the only resource to be reclaimed is memory. The memory will be reclaimed during garbage collection with the rest of the MemoryStream object when your code no longer references the MemoryStream .

Do I need to close Streamreader?

1 Answer. No, there is no need to explicitly call reader. Close if the reading process is inside a using block. By using a using statement (that sounds awkward out loud) everything will be closed and disposed when the code exits the block.

Does stream dispose close stream?

Stream Dispose() also calls Close() if it hasn't already been closed. So your Close() calls are redundant.


1 Answers

With a MemoryStream it is a bit of a moot point - since you are ultimately talking to a managed byte[] (so it is still going to wait for routine garbage collection). But in general, yes: you should close (better: Dispose() via using, so it gets shut down upon exception) the stream when done, otherwise you might not flush some data to the underlying (unmanaged) destination. And there are some streams that don't actually fully "flush" on Flush() - they need to be Close()d (compression streams in particular).

like image 102
Marc Gravell Avatar answered Oct 16 '22 23:10

Marc Gravell