繁体   English   中英

清除与大列表关联的内存

[英]Clearing the memory associated to a large List

我遵循了这个SO问题中的建议。 它对我不起作用。 这是我的情况以及与之相关的代码

我的清单很大,里面有204万个物品。 我将其读入内存以对其进行排序,然后将其写入.csv文件。 我有11个.csv文件需要阅读,然后进行排序。 第一次迭代使我的内存使用量刚刚超过1GB。 我尝试将列表设置为null 我尝试调用List.Clear()我也尝试了List.TrimExcess() 我也一直在等待GC做它的事情。 希望它知道没有读取或写入该列表的信息。

这是我正在使用的代码。 任何建议总是很感激。

foreach (var zone in zones)
{

    var filePath = string.Format("outputs/zone-{0}.csv", zone);

    var lines = new List<string>();

    using (StreamReader reader = new StreamReader(filePath))
    {

        var headers = reader.ReadLine();

        while(! reader.EndOfStream)
        {
            var line = reader.ReadLine();

            lines.Add(line);
        }

        //sort the file, then rewrite the file into inputs

        lines = lines.OrderByDescending(l => l.ElementAt(0)).ThenByDescending(l => l.ElementAt(1)).ToList();

        using (StreamWriter writer = new StreamWriter(string.Format("inputs/zone-{0}-sorted.csv", zone)))
        {
            writer.WriteLine(headers);
            writer.Flush();

            foreach (var line in lines)
            {
                writer.WriteLine(line);
                writer.Flush();
            }
        }

        lines.Clear();
        lines.TrimExcess();

    }
}

尝试将整个内容放入using

using (var lines = new List<string>())
{ ... }

尽管我不确定using s嵌套。

相反,在有行的lines.Clear; ,添加lines = null; 那应该鼓励垃圾收集器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM