c# – 内存不足异常
发布时间:2020-12-16 02:01:46 所属栏目:百科 来源:网络整理
导读:我有一个类型列表,其中包含(字符串,字符串,整数,日期时间,日期时间) 字符串组合中的字符总数等于28. 我在一个文件中读到填充列表,该列表将在列表中以19,000,000(一千九百万)个这些对象结束. 我在文件中读到并添加到列表中 public void ReadDocGrabValues(str
我有一个类型列表,其中包含(字符串,字符串,整数,日期时间,日期时间)
字符串组合中的字符总数等于28. 我在一个文件中读到填充列表,该列表将在列表中以19,000,000(一千九百万)个这些对象结束. 我在文件中读到并添加到列表中 public void ReadDocGrabValues(string fileREAD) { using (var file = new StreamReader(fileREAD)) { var j = file.ReadLine(); while (j != null) { mylist.Add(new IDandAGE(j.Substring(0,15),j.Substring(16,1),j.Substring(18,6),j.Substring(25,DateTime.Today,DateTime.Today)); j = file.ReadLine(); } } } 哪个应该不是问题.然后,我遍历整个列表,从两个字符串中计算出DateTime对象. public void ConvertYOBDOI() { foreach (IDandAGE x in mylist) { string IssueDate = (x.StringDOD.Substring(0,4) + "-" + x.StringDOD.Substring(4,2) + "-01"); string BirthDate = (x.StringYOB.Substring(0,4) + "-" + x.StringYOB.Substring(4,2) + "-01"); x.DeathDate= DateTime.Parse(DeathDate); x.YearOfBirth = DateTime.Parse(BirthDate); } } 然后我再次浏览整个列表以计算出年龄值. public void DateCalc() { foreach (IDandAGE w in mylist) { w.Age = w.DateOfDeath.Year - w.YearOfBirth.Year; if (w.YearOfBirth > w.DateOfDeath.AddYears(-w.Age)) w.Age--; } } 最后,我将列表中的值写入文件. public void CreateAgeFile() { StreamWriter a = new StreamWriter(@"C:GetAgeTest.txt"); foreach (IDandAGE x in mylist) { String f = (x.ID + "," + x.Gender + "," + x.StringYOB + "," + x.StringDOD + "," + x.Age + ",NULL,NULL"); a.WriteLine(f); } a.Close(); } 我真的只是开始编码,所以提前道歉,因为它效率低下/垃圾/无法回答我自己的问题. 我想,由于我多次遍历列表,因此有多种原因可能会给我这个例外. 欢迎任何帮助或建议. 谢谢. 解决方法
如果您正在访问19M记录,那么是:您至少需要考虑内存.您当前将它们全部存储在列表中,因此它们将无法收集.如果您使用的是32位(或64位启用,并且选择了prefer-32位),那么这将是紧张的.一个更好的想法可能是使用迭代器块,这样你就不需要在内存中同时使用它们了:
public IEnumerable<IDandAGE> ReadDocGrabValues(string fileREAD) { foreach(string j in File.ReadLines(fileREAD)) { yield return new IDandAGE(j.Substring(0,DateTime.Today); } } ... foreach (IDandAGE w in ReadDocGrabValues(path)) { // do per-item processing } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |