简体   繁体   English

在 C# 中处理大列表时出现 OutOfMemoryException

[英]OutOfMemoryException when processing large list in C#

I have to process some big tabular data files (ex.: 300.000 rows by 200 columns), creating a data structure for each cell.我必须处理一些大的表格数据文件(例如:300.000 行 x 200 列),为每个单元格创建一个数据结构。

However, in a few thousands iterations a System.OutOfMemoryException is thrown (computer has 8GB RAM).但是,在几千次迭代中,会抛出 System.OutOfMemoryException(计算机有 8GB RAM)。

In my case, I parse each line as a List of Dictionary, since I must have the column name and the value, and process it by creating a node with these information.在我的例子中,我将每一行解析为一个字典列表,因为我必须有列名和值,并通过使用这些信息创建一个节点来处理它。

Here is the code:这是代码:

// foreach record 
foreach (Dictionary<string, string> inst in c.TodasInstancias)
{
instance = null;
tmp = null;

// for each column
foreach (KeyValuePair<string, string> kv in inst)
{
    if ((tmp = this.Relations.Find(new Predicate<Relacionamento>(x => x.Target.Name == kv.Key))) != null)
   { // if this class has a relationship with other classes
       p = og.CreateUriNode(this.UriOntologiaPrefix + ":" + kv.Key);
       o = og.CreateUriNode(new Uri(tmp.CampoOrigem.Classe.Configs.Name_space + "/" + kv.Value));
       og.Assert(instancia, p, o);
   }
   else (kv.Key != c.Configs.Identificador)
   { // se for um campo comum de dados
       p = og.CreateUriNode(this.UriOntologiaPrefix + ":" + kv.Key);
       o = og.CreateLiteralNode(kv.Value);
       og.Assert(instancia, p, o);
   }
}
}

Any hint on how to bypass this exception?有关如何绕过此异常的任何提示?

Use queryable to handle big lists.使用可查询来处理大列表。 You can retrieve batch of records, instead of all data you need using Skip and Take.您可以使用 Skip and Take 检索批量记录,而不是您需要的所有数据。 This way you will handle a small list in memory each time.这样你每次都会在内存中处理一个小列表。 Ex:前任:

   var count=context.entities.Count(); 

   for(i=0,i<count,i+=1000)//1000 can be any size of batch
   {
       var batch =context.entities.Skip(i).Take(1000);
       //Do Operations you need
   }

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

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