How to Dispose a list of objects;Does it Free the Memory [duplicate]

99封情书 提交于 2019-12-24 16:46:29

问题


I have the following class.

public class Foo
{
    private string _DirName;
    private FileStream  _MyfileStream;
    public FileStream  MyfileStream
    {
        get { return _MyfileStream; }               
    }

    public string DirName
    {
        get { return _DirName; }
        set 
        { 
            _DirName = value;
            _MyfileStream = new FileStream(value, FileMode.Create); 
        }
    }            
}

I have Created a List Of Foo as like the following:

List<Foo> FooList = new List<Foo>();
FooList.Add(new Foo() { DirName = @"F:\sample\sample.txt" });
FooList.Add(new Foo() { DirName = @"D:\sample\file.pdf" });

So each list item is creating a File stream. hence the number of streams increased as the number of list item increases. how can i dispose the allocated memory for these streams?


回答1:


All Foo objects and their opened streams will remain in memory and not garbage-collected while the FooList object remains reachable from any point in your application. For example, if FooList is a static member variable, or an instance member variable in a WinForm, that would be the case.

On the other hand, if FooList is a local variable in a method, once the method exist FooList would no longer be reachable and the list and Foo objects would sooner or later be garbage-collected. I'm pretty sure your open streams would be garbage-collected, too. They will be closed automatically through the finalizer.

Using explicit Dispose methods is in most situations optional. Generally, Dispose is used to deterministically free shared resources, such as file streams, open network ports, etc. Classes that require Dispose generally invoke Dispose from the finalizer as well to guarantee clean-up at garbage collection time if the developer/program did not do this at an earlier time. However, having file streams open in your Foo class will not prevent them from being garbage-collected.

Also, listen to CodeCaster and M.kazem and don't open the streams immediately if you don't use them immediately. This is just consuming resources and locking files unnecessarily.




回答2:


Probably Foo should implement IDisposable. You can then iterate that FooList and call Dispose on each item when you no longer need it.



来源:https://stackoverflow.com/questions/32412641/how-to-dispose-a-list-of-objectsdoes-it-free-the-memory

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