Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架OutOfMemoryException的解释与解决方案_C#_Entity Framework_Sqlite_Code First - Fatal编程技术网

C# 实体框架OutOfMemoryException的解释与解决方案

C# 实体框架OutOfMemoryException的解释与解决方案,c#,entity-framework,sqlite,code-first,C#,Entity Framework,Sqlite,Code First,假设我有一个DbContext&实体,如下所示: class Node { public int Id { get; set; } public string Name { get; set; } public int ParentId { get; set; } [ForeignKey("ParentId")] public Node Parent { get; set; } public virtual ICollection<No

假设我有一个
DbContext
&实体,如下所示:

class Node
{
    public int Id { get; set; }

    public string Name { get; set; }
    public int ParentId { get; set; }

    [ForeignKey("ParentId")]
    public Node Parent { get; set; }

    public virtual ICollection<Node> Nodes { get; set; }
}

class MyContext : DbContext
{
    public DbSet<Node> Nodes { get; set; }

    public void ScanChildren(Node parentNode, Action<Node> onFound)
    {
        var query = this.Nodes.Where(X => X.ParentId == parentNode.Id);
        var children = query.ToArray();

        // if I comment this line I get OOME
        System.Windows.Forms.Application.DoEvents();

        foreach (var child in children)
        {               
            onFound(child);
            ScanChildren(child, onFound);
        }
    }
}

static class test
{
    static void ScanTest()
    {
        using (var db = new MyContext())
        {
            var nodeToScan = db.Nodes.First();
            var childrenlist = new List<Node>();
            db.ScanChildren(nodeToScan, x => childrenlist.Add(x));
        }
    }
}

有没有更好的方法来避免DoEvents方面的
OutOfMemoryException

关于DoEvents,在msdn.microsoft.com/en us/library/…您可以阅读“通常,您在循环中使用此方法来处理消息”。因此,我直觉地认为您正在阻塞UI线程中运行这个长时间运行的ScanChildren进程,如果是这样的话,它可能会阻止某些事件消息的正常处理流,这些消息正在缓冲区中排队,最终导致内存不足异常。尝试在后台线程中运行查询。

是否正在运行x64构建?还是x86?@teovankot我运行x86你能改变它吗?您的问题可能可以通过此解决。我的软件也必须在x86机器上运行。您确实需要同时将所有600.000条记录存储在内存中吗?与其将它们全部加载到内存中,不如分批加载和处理它们?(例如,10次迭代的60.000条记录)<代码>跳过和
获取
可用于此操作。
System.Windows.Forms.Application.DoEvents();