Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.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# 实体框架核心-通过锁{}实现线程安全和上下文锁定。我的选择好吗?_C#_Entity Framework_Linq_Entity Framework Core - Fatal编程技术网

C# 实体框架核心-通过锁{}实现线程安全和上下文锁定。我的选择好吗?

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();

我使用gRPC构建了API服务端点。我有一个类来实现数据库操作:

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();
            }