I have a MySQL Server which I access using Entity Framework 4.0. In the database I have a table called Works into which some counts. I develop web site with Asp.net. This table acccesable one more user same time. And this situation causes wrong incerement problem.
My code like that:
dbEntities myEntity = new dbEntities();
var currentWork = myEntity.works.Where(xXx => xXx.RID == 208).FirstOrDefault();
Console.WriteLine("Access work");
if (currentWork != null)
{
Console.WriteLine("Access is not null");
currentWork.WordCount += 5;//Default WordCount is 0
Console.WriteLine("Count changed");
myEntity.SaveChanges();
Console.WriteLine("Save changes");
}
Console.WriteLine("Current Count:" + currentWork.WordCount);
If one more than thread access the database same time, only last changes remain.
Current Output:
t1: Thread One - t2: Thread Two
t1: Access work
t2: Access work
t2: Access is not null
t1: Access is not null
t1: Count changed
t2: Count changed
t1: Save changes
t2: Save changes
t1: Current Count: 5
t2: Current Count: 5
Expected Output:
t1: Access work
t2: Access work
t2: Access is not null
t1: Access is not null
t1: Count changed
t2: Count changed
t1: Save changes
t2: Save changes
t1: Current Count: 5
t2: Current Count: 10
I know why apeear this problem, because this code is not atomic. How can i turn atomic operation?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…