在 C# 中使用 Updlock 和 Readpast

Using Updlock and Readpast in C#

我希望同时读取和更新数据库中的记录。此时,我已经设置了一个示例程序,可以从具有特定状态的数据库中获取记录。

我的目标是在 select 命令执行时锁定行。此代码块执行时没有任何错误,但是在事务的生命周期内行不会锁定。是否支持这些提示或是否有办法做到这一点?

这是 Visual Studio 代码。稍后我会添加更新命令。

SqlDataReader data;
DataTable table = new DataTable();    
string query = string.Format(@"select * from [{0}] with (updlock,readpast) where [status] = '{1}'","table","abc");

using (SqlConnection conn = new SqlConnection(connStr))
{
    conn.Open();

    SqlTransaction trans = conn.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);

    SqlCommand cmd = new SqlCommand(query, conn, trans);
    data = cmd.ExecuteReader();
    table.Load(data);

    System.Threading.Thread.Sleep(15000); // to test locking
}

这是我在 SQL 服务器中测试的原始事务。这很好用。

BEGIN TRAN TEST
   select * from table with (updlock, readpast) where status = 'abc';
   WAITFOR DELAY '00:00:15' 
COMMIT

测试时,我使用 SQL 服务器和 运行 一个 select 语句来检查我是否可以读取锁定的行。我忽略了向 select 查询添加 UPDLOCK 和 READPAST 提示。此代码按预期工作。

我结束了 运行 C# t运行saction,等待时间为 30 秒才完成。在这 30 秒内,我 运行 在 SQL 服务器中执行这些命令以测试行是否已锁定;

select * from table with (updlock, readpast) where status = 'abc';
update table with (readpast) set status = 'cba' where status = 'abc';

行已锁定且无法更新。但是,仍然可以使用 select 语句不带提示地读取它们。这对我正在升级的系统来说应该没问题。