字符串内存分配(需要紧急帮助) [英] string memory allocation (urgent help needed)

查看:79
本文介绍了字符串内存分配(需要紧急帮助)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在读一个大到10-20 MB的大文件,一行在1行以下



string [] lines = System.IO.File.ReadAllLines(file_name);



我将每行保存到数据库,并处理连接。



现在当我再次执行此操作时,Windows应用程序因内存不足而崩溃。



我在第一次读操作时看到内存增加,并且在操作完成时没有释放。



如何释放分配给该字符串的内存。

谢谢,

Shreyas

解决方案

保持连接打开,只需更改命令对象即可插入,如果你的系统上至少有2Gb的内存,那么一个10-20Mb的文件读完就没什么了。


不,你不能。您无法控制内存释放。它是由垃圾收集器在某个对象变得无法访问之后的某个时刻完成的,并且您无法控制它何时发生。请参阅:

http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science %29 [ ^ ]。



您用 ReadAllLines 读取的文件可能太大了。相反,您可以使用类 System.IO.StreamReader 并使用 System.IO.StreamReader.ReadLine

http://msdn.microsoft。 com / en-us / library / system.io.streamreader.aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline.aspx [ ^ ]。



它可以帮助你将文件分成较小的块,并一次一个地处理这些块。



-SA

Hi,

I am reading a large file upto 10-20 MB in a string in 1 go in below line

string[] lines = System.IO.File.ReadAllLines(file_name);

I save each line to database , and dispose the connection.

Now when i again do this operation , the windows app crashes with out of memory exception.

I see during first read operation memory increases and is not freed when operation completes.

How can i free the memory allocated to this string.
Thanks,
Shreyas

解决方案

Keep your connection open and just change your command object for inserting, if you have at least 2Gb memory on your system then a 10-20Mb file read in full is nothing.


No, you cannot. You don't have control over the memory deallocation. It is done by the Garbage Collector at some moment of time after some object become unreachable, and you don't control when exactly it happens. Please see:
http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29[^].

Perhaps the file you read with ReadAllLines is just too big. Instead, you can use the class System.IO.StreamReader and read the data line by line using System.IO.StreamReader.ReadLine:
http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx[^],
http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline.aspx[^].

It would help you to divide a file by smaller chunks and do something with those chunks one at a time.

—SA


这篇关于字符串内存分配(需要紧急帮助)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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