How to Dispose a list of objects;Does it Free the

2019-08-05 02:14发布

This question already has an answer here:

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?

2条回答
Viruses.
2楼-- · 2019-08-05 02:42

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

查看更多
迷人小祖宗
3楼-- · 2019-08-05 02:54

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.

查看更多
登录 后发表回答