序列化对象保存在硬盘上,造成内存一直在涨.有人碰到过这个问题吗?

xieqi 2011-02-09 11:31:50
具体代码很短.
===================================
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
for (int j = 0; j < 20000; j++)//创建20000个对象
{
List<int> obj_list = new List<int>();
for (int i = 1; i < 3000; i++)//创建一个list对象
{
obj_list.Add(i);
}
string path = @"D:\c#\ConsoleApplication2\cache\" + j;//保存的路径
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, obj_list);//序列化保存在硬盘上
}
if (j % 300==0)//每300次输出一下
{
Console.WriteLine(j);
}
}
}
}
}
===========================================
问题来了,这个程序执行的时候,该进程占了15mb内存(基本固定不变),然后随着程序一直执行,系统占用内存不断增加.
然后把程序关了.系统就释放了15mb内存.还有1大块内存被无缘无故吃了.

然后到D:\c#\ConsoleApplication2\cache\ 下执行 del *.*
删除文件时,系统占用内存不断减少.

随着文件被删完,内存不断的释放出来了?怎么回事?


...全文
171 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
phil999 2011-02-09
  • 打赏
  • 举报
回复
找个内存整理程序试试
ttyyadd 2011-02-09
  • 打赏
  • 举报
回复
强制内存回收试试
xieqi 2011-02-09
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 sprc_lcl 的回复:]

试一下这样
C# code
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
BinaryFormatter formatter = new BinaryFormatter();
……
[/Quote]
问题依旧
我就不明白,保存成文件了,进程也退出了,怎么就内存一直占着,文件删了,内存就释放了?
xieqi 2011-02-09
  • 打赏
  • 举报
回复
我为每个用户保存一个List<int>,有40w以上的用户.
怎么减少循环呢?
flyerwing 2011-02-09
  • 打赏
  • 举报
回复
楼主撞到了国际领先问题.
没碰到过了.
wuyq11 2011-02-09
  • 打赏
  • 举报
回复
循环次数太多,重设计逻辑
sprc_lcl 2011-02-09
  • 打赏
  • 举报
回复
试一下这样
                FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, obj_list);//序列化保存在硬盘上
fs.Close();
fs.Dispose();
threenewbee 2011-02-09
  • 打赏
  • 举报
回复
为什么要创建这么多对象。
半截烟头 2011-02-09
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 xieqi 的回复:]
我为每个用户保存一个List<int>,有40w以上的用户.
怎么减少循环呢?
[/Quote]

如果这么多,为什么不用数据库或文件来实现,有必要全部一次性装入内存吗?
sjllwj520 2011-02-09
  • 打赏
  • 举报
回复
内存保存的是Page File 虚拟内存的文件。你的fs.close 要加上的话内存会释放,虚拟内存是用的时候才删的。

110,546

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧