实体.ToList()生成一个System.OutOfMemoryException [英] entity .ToList() generates a System.OutOfMemoryException

查看:325
本文介绍了实体.ToList()生成一个System.OutOfMemoryException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有十万行的表。我需要更新每一行,但了ToList()失败:

I have a table with half a million rows. I need to update every single row but the ToList() fails:

List<Contacts> allContacts = objDatabase.Contacts.ToList();

我每次都得到一个System.OutOfMemoryException。有没有解决的办法吗?

I get a System.OutOfMemoryException every time. Is there a way around this?

我已经在app.config的解决方法,但仍然没有去:

I already have the App.Config workaround but still no go:

<gcAllowVeryLargeObjects enabled="true" />    

我是一个64位的机器8GB的RAM上

I'm on a 64bit machine with 8GB of RAM

推荐答案

下面是用分块解决方案。它将处置容器(和下载的实体),每块后。内存应该由GC系统不久被释放内存用完。

Here is a solution using chunking. It will dispose of the container (and the downloaded entities) after every chunk. Memory should be released by the GC long before your system runs out of memory.

int chunkSize = 50;
int curCount = 0;

while (true)
{
    using (var db = new DbEntities())
    {
        var chunk = db.Contacts.Skip(curCount).Take(chunkSize).ToArray();
        curCount += chunkSize;

        if (chunk.Length == 0) break;

        foreach (var contact in chunk)
        {
            //do any work for the contact here
            contact.Something = "SomethingNew";
        }

        db.SaveChanges();
    }
}

随意玩弄的块大小。较大的块,更快的整个过程应该是,但它会占用更多的内存。

Feel free to play around with the chunk size. The larger the chunk, the faster the entire process should be, but it will use up more memory.

这篇关于实体.ToList()生成一个System.OutOfMemoryException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆