如何处理对象列表;是否释放了内存 [英] How to Dispose a list of objects;Does it Free the Memory

查看:106
本文介绍了如何处理对象列表;是否释放了内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程.

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); 
        }
    }            
}

我已经创建了一个Foo列表,如下所示:

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?

推荐答案

所有Foo对象及其打开的流将保留在内存中,不会被垃圾回收,而FooList对象仍可从应用程序中的任何位置访问.例如,如果FooList是静态成员变量,或者是WinForm中的实例成员变量,那就是这种情况.

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.

另一方面,如果FooList是方法中的局部变量,则一旦该方法存在,FooList将不再可访问,并且list和Foo对象或早或晚将被垃圾回收.我很确定您的开放流也将被垃圾收集.它们将通过终结器自动关闭.

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.

在大多数情况下,使用显式Dispose方法是可选的.通常,Dispose用于确定性地释放共享资源,例如文件流,开放的网络端口等.需要Dispose的类通常也从终结器调用Dispose,以确保在开发人员/程序未进行垃圾回收时进行清理.尽早这样做.但是,在Foo类中打开文件流不会阻止对其进行垃圾收集.

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.

此外,请收听CodeCaster和M.kazem,如果不立即使用它们,请不要立即打开流.这只是在浪费资源并不必要地锁定文件.

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.

这篇关于如何处理对象列表;是否释放了内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆