Out of memory when creating a lot of objects C#

前端 未结 5 1827
醉梦人生
醉梦人生 2020-12-18 21:26

I\'m processing 1 million records in my application, which I retrieve from a MySQL database. To do so I\'m using Linq to get the records and use .Skip() and .Take() to proce

5条回答
  •  自闭症患者
    2020-12-18 21:35

    Ok I've just discussed this situation with a colleague of mine and we've come to the following solution which works!

    int amountToSkip = 0;
    var finished = false;
    while (!finished)
    {
          using (var dataContext = new LinqToSqlContext(new DataContext()))
          {
               var objects = dataContext.Repository().Skip(amountToSkip).Take(250).ToList();
               if (objects.Count == 0)
                    finished = true;
               else
               {
                    foreach (Object object in objects)
                    {
                        // Create 0 - 4 Random Items
                        for (int i = 0; i < Random.Next(0, 4); i++)
                        {
                            Item item = new Item();
                            item.Id = Guid.NewGuid();
                            item.Object = object.Id;
                            item.Created = DateTime.Now;
                            item.Changed = DateTime.Now;
                            dataContext.InsertOnSubmit(item);
                         }
                     }
                     dataContext.SubmitChanges();
                }
                // Cumulate amountToSkip with processAmount so we don't go over the same Items again
                amountToSkip += processAmount;
            }
    }
    
    
    

    With this implementation we dispose the Skip() and Take() cache everytime and thus don't leak memory!

    提交回复
    热议问题