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

并发可能产生的三种问题

脏读

定义:A事务执行过程中B事务读取了A事务的修改,但是A事务并没有结束(提交),A事务后来可能成功也可能失败。

比喻:A修改了源代码并且并没有提交到源代码系统,A直接通过QQ将代码发给了B,A后来取消了修改。

代码示例

复制代码 代码如下:


[TestMethod]
         public void 脏读_测试()
         {
             //前置条件
             using (var context = new TestEntities())
             {
                 Assert.AreEqual(1, context.Tables.Count());
             }

             var autoResetEvent = new AutoResetEvent(false);

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

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

                 ThreadPool.QueueUserWorkItem(data =>
                 {
                     using (var ts2 = new TransactionScope(TransactionScopeOption.Required, transactionOptions2))
                     {
                         //脏读测试
                         using (var context = new TestEntities())
                         {
                             Assert.AreEqual(2, context.Tables.Count());
                         }
                     }

                     autoResetEvent.Set();
                 });

                 autoResetEvent.WaitOne();
             }

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

不可重复读

定义:A事务读取了两次数据,在这两次的读取过程中B事务修改了数据,A事务的这两次读取出来的数据不一样了(不可重复读)。

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

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