简体   繁体   English

在给定的时间内锁定SQL Server表并检查其是否被锁定

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

I want to lock a table for a given amount of time in SQL Server . 我想在SQL Server中将表锁定给定的时间。 I am using C# at code level. 我在代码级别使用C#。 How can I achieve it, I also need to verify that the table is locked or not. 如何实现它,我还需要验证表是否被锁定。 I do not have much knowledge of locking tables in SQL Server. 我对锁定SQL Server中的表不了解很多。 I want to achieve it using entity framework. 我想使用实体框架来实现它。 Any help is much appreciated. 任何帮助深表感谢。

You can try as shown below. 您可以尝试如下所示。

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

Note : The table lock will be released after it exits the BeginTransaction block 注意:表锁在退出BeginTransaction块后将被释放

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM