Closing streams, always necessary? .net

后端 未结 4 1280
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-17 08:54

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

4条回答
  •  逝去的感伤
    2021-01-17 09:28

    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).

提交回复
热议问题