从多个线程向 DbSet 添加元素的方法
static Object LockEx=new Object();
public void SaveMyData(IEnumerable<MyData> list)
{
lock (LockEx)
{
using (PersistencyContext db = new PersistencyContext())
{
foreach (var el in list)
{
try
{
db.MyData.Add(el);
db.SaveChanges();
}
catch (DbUpdateException)
{
db.Entry(el).State = EntityState.Modified;
db.SaveChanges();
}
}
}
}
}
从多个线程调用此方法。现在我使用静态锁来避免2个线程同时保存数据。虽然这是错误的,因为我只想保存数据。该 catch 用于创建更新查询,以防插入(添加)因条目已存在而失败。
如果我移除锁会发生什么。 SaveChanges
将如何工作?我的代码应该是什么样的?谢谢
static Object LockEx=new Object();
public void SaveMyData(IEnumerable<MyData> list)
{
lock (LockEx)
{
using (PersistencyContext db = new PersistencyContext())
{
foreach (var el in list)
{
try
{
db.MyData.Add(el);
db.SaveChanges();
}
catch (DbUpdateException)
{
db.Entry(el).State = EntityState.Modified;
db.SaveChanges();
}
}
}
}
}
This methods is called from multiple threads. Right now I use a static lock to avoid 2 threads to save data at the same time. Though this is wrong because I only want to save data. The catch is used to create an update query in case the insert (Add) fails because the entry already exists.
What happens if I remove the lock. How will the SaveChanges
work? How should my code look like? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会删除锁,因为数据库已经按设计处理并发性,然后我还将在尝试添加记录之前验证记录是否存在,然后我将根据此结果进行添加或更新。只是为了避免异常,因为它们是性能杀手。
I would remove the lock because the database already handles concurrency anyway by design, then I will also verify if the record exists before trying to add it, then I would do the add or update depending on this result. Just to avoid exceptions because they are performance killers.
根据 Davide 的答案,您还可以在添加所有新实体后调用 SaveChanges 一次。那应该更快。
Building on Davide's answer, you could also call SaveChanges once after you added all the new entities. That should be faster.