gpt4 book ai didi

c# - 多个独立数据库事务的并发问题?

转载 作者:太空狗 更新时间:2023-10-29 23:40:56 25 4
gpt4 key购买 nike

您将如何解决以下代码的并发问题?在这个示例中,我们想知道用户身份验证失败的原因。问题是这段代码对数据库进行了两次单独的调用,但我们希望整个方法发生在一个概念性事务中。具体来说,我们对 isolation 感兴趣.在我们确定身份验证失败的原因之前,我们不希望执行此方法期间的并发写入影响我们的读取。

我想到了一些解决方案:Thread Locking , TransactionScopeOptimistic Locking .我真的很喜欢乐观锁定的想法,因为我认为冲突可能很少见,但是 .NET 中没有内置任何东西可以做到这一点,对吧?

此外 - 在这种情况下,这真的值得关注吗?像这样的并发问题什么时候需要考虑,什么时候不需要?实现解决方案需要考虑什么?表现?锁定时间?发生冲突的可能性有多大?

编辑:在查看 Aristos 的回答后,我认为我真正想要的是 Authenticate 方法的某种“snapshot”隔离级别。

public MembershipStatus Authenticate(string username, string password)
{
MembershipUser user = Membership.GetUser(username);
if (user == null)
{
// user did not exist as of Membership.GetUser
return MembershipStatus.InvalidUsername;
}

if (user.IsLockedOut)
{
// user was locked out as of Membership.GetUser
return MembershipStatus.AccountLockedOut;
}

if (Membership.ValidateUser(username, password))
{
// user was valid as of Membership.ValidateUser
return MembershipStatus.Valid;
}

// user was not valid as of Membership.ValidateUser BUT we don't really
// know why because we don't have ISOLATION. The user's status may have changed
// between the call to Membership.GetUser and Membership.ValidateUser.
return MembershipStatus.InvalidPassword;
}

最佳答案

根据我的阅读 herehere ,它似乎是一个 System.Transactions.TransactionScope 包装你的整个方法应该自动在一个公共(public)事务中登记你的数据库调用,从而在整个事务范围内实现事务安全。

你想做这样的事情:

public MembershipStatus Authenticate(string username, string password)
{
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Snapshot }))
{
MembershipUser user = Membership.GetUser(username);
if (user == null)
{
// user did not exist as of Membership.GetUser
return MembershipStatus.InvalidUsername;
}

if (user.IsLockedOut)
{
// user was locked out as of Membership.GetUser
return MembershipStatus.AccountLockedOut;
}

if (Membership.ValidateUser(username, password))
{
// user was valid as of Membership.ValidateUser
return MembershipStatus.Valid;
}

// user was not valid as of Membership.ValidateUser BUT we don't really
// know why because we don't have ISOLATION. The user's status may have changed
// between the call to Membership.GetUser and Membership.ValidateUser.
return MembershipStatus.InvalidPassword;
}
}

关于c# - 多个独立数据库事务的并发问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9269324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com