簡體   English   中英

在 C# 中處理大列表時出現 OutOfMemoryException

[英]OutOfMemoryException when processing large list in C#

我必須處理一些大的表格數據文件(例如:300.000 行 x 200 列),為每個單元格創建一個數據結構。

但是,在幾千次迭代中,會拋出 System.OutOfMemoryException(計算機有 8GB RAM)。

在我的例子中,我將每一行解析為一個字典列表,因為我必須有列名和值,並通過使用這些信息創建一個節點來處理它。

這是代碼:

// 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);
   }
}
}

有關如何繞過此異常的任何提示?

使用可查詢來處理大列表。 您可以使用 Skip and Take 檢索批量記錄,而不是您需要的所有數據。 這樣你每次都會在內存中處理一個小列表。 前任:

   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