Is it ok not to dispose a MemoryStream / StringReader?

末鹿安然 提交于 2019-12-01 08:55:53

Nothing is going to suffer in this case, but IMO it is still very bad practice. You own them - why not do it properly? Actually, disposing a MemoryStream still can't deallocate etc - it is still bound by GC. But there is a distinct code smell in here somewhere. This can become real problems if anything ever changes, and suddenly it isn't a MemoryStream but something else, etc.

We can't make you dispose it, but personally: I am fastidious about my usings

Answer: NO. You should always dispose disposable resources. In the case of returning a stream from a method, the disposal should be done by the caller.

If you allocate a resource for the explicit internal use of your class, then your class owns the responsibility of disposing of that resource. If you are allocating a resource on behalf of a caller, than it is the responsibility of the caller to manage the lifetime of the resources requested.

While the CLR will eventually free resources alliocated by any object, no garentees are made as to when a specific object will be collected (deallocated).

Therefore if an object uses a relatively scarse resource such as a file handle and that object is not disposed of by the code that created it, the file handle will remain unavailable for use by the system or other applications until the garbage collector collects the object holding the handle.

On a single users desktp[ machine, it is unlikely that you would run ouut of file handles, but on a busy server it is more likely that you will approach the maximum number of file handles available, and the closer one gets to exhausting a system resource the more likely it is that the machie will experience performance degradation, so the timely release of resources becomes a much bigger concern.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!