How do you solve the concurrency problem with the following code? In this example, we would like to know why the user did not authenticate. The problem is that this code makes two separate calls to the database, but we would like the whole method to be executed inside a conceptual transaction. In particular, we are interested in isolation . We do not want concurrent writes during the execution of this method to affect our readings before we determine the cause of the authentication failure.
Several solutions come to mind: Thread Lock , TransactionScope, and Optimistic Lock . I really like the idea of ββOptimistic Locking, since I think conflicts are likely to be rare, but there is nothing in .NET to do this, right?
Also - is something REALLY bothering in this case? When concurrency problems like this are important to consider, and when not? What should be considered when implementing a solution? Performance? Lock duration? How likely are conflicts?
Change: . After considering Aristos' answer, I think I'm really in some way a snapshot for the Authenticate method.
public MembershipStatus Authenticate(string username, string password)
{
MembershipUser user = Membership.GetUser(username);
if (user == null)
{
return MembershipStatus.InvalidUsername;
}
if (user.IsLockedOut)
{
return MembershipStatus.AccountLockedOut;
}
if (Membership.ValidateUser(username, password))
{
return MembershipStatus.Valid;
}
return MembershipStatus.InvalidPassword;
}
source