.NET中 关于脏读 不可重复读与幻读的代码示例(3)

比喻:A在统计文件数据,为了统计精确A统计了两次,在这两次的统计过程中B添加了一个文件,A发现这两次统计的数量不一样(幻读),A会感觉自己的脑袋有点头疼。

代码示例

复制代码 代码如下:


[TestMethod]
         public void 幻读_测试()
         {
             var autoResetEvent = new AutoResetEvent(false);

             var transactionOptions1 = new TransactionOptions { IsolationLevel = IsolationLevel.RepeatableRead };
             var transactionOptions2 = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted };

             using (var ts1 = new TransactionScope(TransactionScopeOption.Required, transactionOptions1))
             {
                 //前置条件
                 using (var context = new TestEntities())
                 {
                     Assert.AreEqual(1, context.Tables.Count());
                 }

                 ThreadPool.QueueUserWorkItem(data =>
                 {
                     using (var ts2 = new TransactionScope(TransactionScopeOption.Required, transactionOptions2))
                     {
                         //添加数据
                         using (var context = new TestEntities())
                         {
                             context.Tables.Add(new Table() { Id = Guid.NewGuid(), Name = "段光伟" });
                             context.SaveChanges();
                         }

                         ts2.Complete();
                     }

                     autoResetEvent.Set();
                 });

                 autoResetEvent.WaitOne();

                 //幻读测试
                 using (var context = new TestEntities())
                 {
                     Assert.AreEqual(2, context.Tables.Count());
                 }
             }
         }


四种隔离级别如何处理并发问题
    脏读   不可重复读   幻读  
读未提交   允许   允许   允许  
读已提交   不允许   允许   允许  
可重复读   不允许   不允许   允许  
串行化   不允许   不允许   不允许  

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjgszp.html