.net 事务死锁测试
1 [TestInitialize] 2 public void Initialize() 3 { 4 //Mis系统配置 5 Util6.Information.Config.CoreConfig.Initialize("Default"); 6 IocHelper.Register<MisConfig>(() => CoreConfig.GetConfigInfo<MisConfig>(new MisSettingService().FindList()), true); 7 8 } 9 10 11 [TestMethod] 12 public void TestDeadLock() 13 { 14 var tasks = new System.Collections.Generic.List<System.Threading.Tasks.Task>(); 15 for (int j = 0; j < 10; j++) 16 { 17 tasks.Add(System.Threading.Tasks.Task.Factory.StartNew((obj) => 18 { 19 var storage = new Util6.Information.Repositorys.MisRepositoryStorage(); 20 using (var db = new DbBuilder(CoreConfig.WriteConfig).KeepConnect()) 21 { 22 try 23 { 24 db.BeginTransaction(); 25 var log = storage.MisLogVisit.UseDatabase(db).Query(m => m.ID == 2).ToEntity(); 26 storage.MisLogVisit.SetEntity(log); 27 log.Oper = "456" + obj; 28 storage.MisLogVisit.UseDatabase(db).Update(); 29 //死锁异常 30 //var logInfo = storage.MisLogVisit.UseDatabase(null).Query().ToCount(); 31 //没有在锁定行查询则没有问题 32 //var logInfo = storage.MisLogVisit.UseDatabase(null).Query(m=>m.ID != 2).ToCount(); 33 //用事务连接的对象则没有问题 34 var logInfo = storage.MisLogVisit.UseDatabase(db).Query().ToCount(); 35 db.CommitTransaction(); 36 } 37 catch (Exception ex) 38 { 39 Console.WriteLine(ex.ToString()); 40 db.RollbackTransaction(); 41 } 42 } 43 }, j)); 44 tasks.Add(System.Threading.Tasks.Task.Factory.StartNew((obj) => 45 { 46 var storage = new Util6.Information.Repositorys.MisRepositoryStorage(); 47 //事务外不会引起死锁异常 48 var logInfo = storage.MisLogVisit.Query().ToCount(); 49 System.Threading.Thread.Sleep(1); 50 }, j)); 51 } 52 System.Threading.Tasks.Task.WaitAll(tasks.ToArray()); 53 Console.WriteLine("end"); 54 }