比喻:A在做源代码审查,在审查的过程中获取了两次源代码,在这两次获取期间B修改了源代码,B修改的很可能是A审查过的代码,而这部分代码可能不符合规范了。
代码示例
复制代码 代码如下:
[TestMethod]
public void 不可重复读_测试()
{
var autoResetEvent = new AutoResetEvent(false);
var transactionOptions1 = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted };
var transactionOptions2 = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted };
using (var ts1 = new TransactionScope(TransactionScopeOption.Required, transactionOptions1))
{
//前置条件
using (var context = new TestEntities())
{
Assert.AreEqual("李妞妞", context.Tables.First().Name);
}
ThreadPool.QueueUserWorkItem(data =>
{
using (var ts2 = new TransactionScope(TransactionScopeOption.Required, transactionOptions2))
{
//修改数据
using (var context = new TestEntities())
{
context.Tables.First().Name = "段光伟";
context.SaveChanges();
}
ts2.Complete();
}
autoResetEvent.Set();
});
autoResetEvent.WaitOne();
//不可重复读测试
using (var context = new TestEntities())
{
Assert.AreEqual("段光伟", context.Tables.First().Name);
}
}
}
幻读
定义:A事务读取了两次数据,在这两次的读取过程中B事务添加了数据,A事务的这两次读取出来的集合不一样了(幻读)。