在给定时间内锁定 SQL 服务器 Table 并检查它是否被锁定

Lock a SQL server Table for a given time and check if it is locked

我想在 SQL 服务器中锁定 table 给定的时间。我在代码级别使用 C#。我怎样才能实现,我还需要验证 table 是否被锁定。我不太了解在 SQL 服务器中锁定 tables。我想使用 entity framework 来实现它。非常感谢任何帮助。

您可以尝试下图

using (var context = new YourContext())
    {
     using (var dbContextTransaction = context.Database.BeginTransaction())
     {
       //Lock the table during this transaction
       context.Database.ExecuteSqlCommand("SELECT 1 FROM YourTable WITH (TABLOCKX)
    WAITFOR DELAY '00:03:00'");

            //your work here

            dbContextTransaction.Commit();
      }
}

注:table锁在退出BeginTransaction

后会被释放