How do I avoid a memory leak with LINQ-To-SQL?

后端 未结 5 1883
轮回少年
轮回少年 2020-12-08 15:47

I have been having some issues with LINQ-To-SQL around memory usage. I\'m using it in a Windows Service to do some processing, and I\'m looping through a large amount of da

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 16:11

    Thanks guys - I will check out the ClearCache method. Just for clarification (for future readers), the situation in which I was getting the memory usuage was something like this:

    using(DataContext context = new DataContext())
    {
       while(true)
       {
          int skipAmount = 0;
          var rows = context.tables.Select(x => x.Dept == "Dept").Skip(skipAmount).Take(100);
    
          //break out of loop when out of rows
    
          foreach(table t in rows)
          {
             //make changes to t   
          }
    
          context.SubmitChanges();
          skipAmount += rows.Count();
    
          rows.Clear();
          rows = null;
    
          //at this point, even though the rows have been cleared and changes have been
          //submitted, the context is still holding onto a reference somewhere to the
          //removed rows.  So unless you create a new context, memory usuage keeps on growing
       }
    }
    

提交回复
热议问题