c# - 为每个插入创建 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 与长期数据库连接一起使用的正确方法是什么?
解决方案
推荐阅读
- java - 1 被添加到输出中,同时迭代地计算“e”的值
- dart - “'child.parent == this':不是真的。”。将文本字段放入列表视图时出现此错误。(扑)
- mysql - 在 JOIN 期间从单个查找表连接多个表
- react-native - 如何在 Victory 中复制这样的图表?
- facebook - Facebook publish_actions 已弃用:上传照片
- bash - 如何分隔逗号分隔的文件并将每个单词放在变量中?
- typescript - 在 Typescript 中,如何使用扩展语法为 querySelectorAll 设置类型
- database - DOS Clipper 应用程序的导出数据库
- linux - docker容器中的奇怪文件权限(权限位和用户位上的问号)
- html - Python 3:如何从包含多个类值的 div 中抓取文本