服务器故障转移后 TransactionScope 是否仍在运行,服务器故障转移时数据库如何自动回滚更改?

Is TransactionScope still running after server failover and how does the database roll back the changes automatically when the server failover?

提问人:Abd Al-Rahman Odeh 提问时间:11/9/2023 最后编辑:Dale KAbd Al-Rahman Odeh 更新时间:11/10/2023 访问量:48

问:

这是我的代码

 using (var context = DbContextCreator.Create())
    {
        var transactionOptions = new TransactionOptions { Timeout = TransactionManager.DefaultTimeout }; // 60 seconds. 

        using (var dbContextTransaction = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
        {
            try
            {
                context.Database.ExecuteSqlCommand("SELECT TOP 1 Id FROM SRE.ActionHistory WITH (TABLOCKX, HOLDLOCK)");

                bool isDuplicated = context.ActionHistory
                    .Any(x => x.StatusId == (int)eActionHistoryStatus.Pending &&
                                x.ActionId == (int)Action &&
                                x.DateTime >= timeToCheck &&
                                x.CustomerId == Customer.Id);
                if (!isDuplicated)
                {
                    context.ActionHistory.Add(actionHistory);
                    context.SaveChanges();
                    dbContextTransaction.Complete();
                    return actionHistory;
                }
                throw new BizException(BizErrorCodes.NotAllowedToDoAction);
            }
            catch (Exception ex)
            {
                // It will roll back automatically if the Complete() method isn't invoked or the timeout takes longer than the specified timeout.
                throw;
            }

        }

    }
}

我有两台服务器,一台用于 .NET 代码,另一台用于数据库。

我期望故障转移的服务器是保存 .NET 代码的服务器。

实际上,即使服务器出现故障,我也需要释放锁。

为了使我的代码干净,我应该使用哪个 Transaction Scope 或 BeginTransaction?

C# SQL-Server 实体框架 事务 TransactionScope

评论

0赞 Dan Guzman 11/9/2023
我希望 SQL Server 会在 SQL 客户端连接因故障转移而终止时回滚事务。
0赞 Charlieface 11/9/2023
TransactionScope在使用方面更干净(因为自动登记),但可能更有效率。 是浪费时间,还不如不抓。 是个坏主意,因为它把一个完整的块放在桌子上。最好在 a 中完成并只读取您需要的行。BeginTransactioncatch (Exception ex) { throw; }TABLOCKX, HOLDLOCKUPDLOCK, HOLDLOCKFromSqlRaw

答:

0赞 David Browne - Microsoft #1

当 SQL 客户端连接因故障转移而终止时,SQL Server 将回滚事务。