C# For循环-内存不足异常
事实上,我得到了一个类似于C# For循环-内存不足异常,c#,for-loop,memory-management,garbage-collection,out-of-memory,C#,For Loop,Memory Management,Garbage Collection,Out Of Memory,事实上,我得到了一个类似于saveindb加密格式的9位数字组合的要求 因此,我使用了一种非常基本的加密算法,并考虑使用for循环直到99999999并将记录保存在DataTable和BulkCopy to SQL中 我的程序是这样的: DataTable DtData = new DataTable(); DtData.Columns.Add("ENCRYPTED_DATA", typeof(string)); for (Int64 i = 1; i <= 999999
saveindb
加密格式的9位数字组合的要求
因此,我使用了一种非常基本的加密算法,并考虑使用for循环直到99999999
并将记录保存在DataTable
和BulkCopy to SQL
中
我的程序是这样的:
DataTable DtData = new DataTable();
DtData.Columns.Add("ENCRYPTED_DATA", typeof(string));
for (Int64 i = 1; i <= 999999999; i++)
{
string Number = i.ToString("D9");
string Encrypt = EncryptDecrypt.Encrypt(Number);
DtData.Rows.Add(Encrypt);
if (i % 100000 == 0)
{
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
}
}
DataTable DtData=newdatatable();
添加(“加密的_数据”,typeof(string));
对于(Int64 i=1;i您的DtData正在填满并占用您的所有内存
世界上所有的垃圾收集都没有用
将数据保存到数据库中,然后清空DtData数据表。行
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
无法释放DataTable DtData
中已有的数据。我不知道您正在创建的字符串的大小,但您正在创建数千个字符串并将它们添加到DataTable DtData
DtData
中的这些字符串在此循环范围内永远不符合垃圾收集的条件
您应该定期将这些数字提交到数据库,如下所示
DataTable DtData = new DataTable();
DtData.Columns.Add("ENCRYPTED_DATA", typeof(string));
for (Int64 i = 1; i <= 999999999; i++)
{
string Number = i.ToString("D9");
string Encrypt = EncryptDecrypt.Encrypt(Number);
DtData.Rows.Add(Encrypt);
//vary this number depending on your performance testing and application needs
if (i % 100000 == 0)
{
//instead of this
//GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
//commit changes and refresh your DataTable
DoSomeDatabaseCommitHere(DtData);
DtData = new DataTable();
}
}
DataTable DtData=newdatatable();
添加(“加密的_数据”,typeof(string));
对于(Int64 i=1;i)您的内存不足,因为您的内存不足。您希望得到什么?确定。如果(i%100000==0),将尝试将记录保存到数据库中条件并清除DataTable。是的。我将尝试一下。感谢您的支持,因为我计算出完成整个周期需要17个多小时。有没有办法让它变快?如果我使用列表来代替DataTable,它会有帮助吗?列表应该更快,尽管哈希集可能更有效。有关列表v的更多信息,请参阅s HashSet。如果(i%100000==0)
,也可以将行修改为更大的数字,以减少批量提交。此外,您可以查看在加密时使用后台线程进行提交。请参阅我的链接,了解有助于此的各种收集类。