首页 > 解决方案 > 为每个插入创建 EF 数据库实例?

问题描述

我有一个工作线程,其工作是将存储在队列中的对象插入数据库。

我们目前正在使用实体框架来进行插入。现在我的问题是,我是否需要为每个插入创建一个新的数据库实例?或者我可以安全地反复使用同一个数据库实例吗?

private static void MainWorker()
    {            
        while (true)
        {
            try
            {
                if (IncomingDataQueue.Any())
                {              
                    if (IncomingDataQueue.TryDequeue(out var items))
                    {
                        //Insert into db
                        using (var db = GetNewDbInstance())
                        {
                            if (db != null)
                            {
                                db.DataRaw.AddRange(items);
                                db.SaveChanges();
                                //Skip everything and continue to the next loop
                                continue;
                            }
                        }
                    }
                }
            }                
            catch (Exception ex)
            {
                Debug.WriteException("Failed to insert DB Data", ex);
                //Delay here in case we are hitting the db 2 hard.
                Thread.Sleep(100);
            }
            //Wait here as we did not have any items in the queue, so wait before checkign again
            Thread.Sleep(20);
        }
    }

这是我获取新数据库实例的函数:

  private static DbEntities GetNewDbInstance()
    {
        try
        {
            var db = new DbEntities();
            db.Configuration.ProxyCreationEnabled = false;
            db.Configuration.AutoDetectChangesEnabled = false;
            return db;
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Error in getting db instance" + ex.Message);
        }
        return null;
    }

现在我到目前为止还没有遇到任何问题,但是,我担心如果我们每分钟插入 1000 次,这个解决方案将无法很好地扩展?

然后我还担心使用 1 个静态数据库实例可能会导致内存泄漏,或者该对象会继续增长并且无法正确管理它的数据库连接?

将 EF 与长期数据库连接一起使用的正确方法是什么?

标签: c#databaseentity-framework

解决方案


推荐阅读