C# 实体框架核心-通过锁{}实现线程安全和上下文锁定。我的选择好吗?
我使用gRPC构建了API服务端点。我有一个类来实现数据库操作:C# 实体框架核心-通过锁{}实现线程安全和上下文锁定。我的选择好吗?,c#,entity-framework,linq,entity-framework-core,C#,Entity Framework,Linq,Entity Framework Core,我使用gRPC构建了API服务端点。我有一个类来实现数据库操作: public SSImpl(BaseContext cnx) { this.cnx = cnx; } 基本上下文是 public class BaseContext : DbContext { public BaseContext() { Database.EnsureDeleted();
public SSImpl(BaseContext cnx)
{
this.cnx = cnx;
}
基本上下文是
public class BaseContext : DbContext
{
public BaseContext()
{
Database.EnsureDeleted();
Database.EnsureCreated();
}
public DbSet<User> _Users { get; set; }
}
现在我在上下文使用方面遇到了问题。在测试中我有例外
A second operation started on this context before a previous asynchronous operation completed.
及
因此,我的问题和想法是:
这是更好地使用它像锁定同步操作
lock (cnx)
{
cnx._Users.Add(new User
{
Nick = nick,
Password = password,
Details = new UserDetails
{
Email = email
}
});
cnx.SaveChanges();
}
为了确保操作1在操作2开始之前完成,或者我应该使用wait
savechangesync
而不是SaveChanges?我不确定,因为现在我不能使用IDisposable上下文,我不知道saveChangesSync
是否会执行类似于数据库操作队列的操作?如果是这样的话,选择什么?这不是有争议的吗?或者我需要使用不同的上下文来创建、更新和阅读 这是错误的。DbContext不是线程安全的,不需要。它不应该在请求之间重用。它表示单个工作单元,这就是为什么它几乎总是在DI中注册为作用域服务的原因。在释放DbContext之前,当代码调用SaveChanges
或saveChangesSync
时,所有更改都会被保存。没有理由多次调用SaveChanges
查看Gunnar Peipman的更多信息。@PanagiotisKanavos好的,所以我的思维方式是错误的。我认为使用上下文是个好主意,甚至在asp.net的粉丝论坛上发现了这个DI是个好主意。好吧,我明白你的答案,我应该回到我的邮箱。所以现在我要换课了。谢谢你。@PanagiotisKanavos很棒的文章,这应该是你对我问题的回答。可能会帮助很多人。
"A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.")'
lock (cnx)
{
cnx._Users.Add(new User
{
Nick = nick,
Password = password,
Details = new UserDetails
{
Email = email
}
});
cnx.SaveChanges();
}