测试代码:
int i = 10;int xx = 20;Listlst = null;Action doSth = () =>{ using (var db = new TestSystemEntities()) { var f = db.ABC.ToList(); f.ForEach(x => x.C = "TestTransactionScope"); db.SaveChanges(); } new Task(() => { using (var db = new TestSystemEntities()) { var f = db.ABC.ToList(); f.ForEach(x => x.C = "AsyncTestTransactionScope"); db.SaveChanges(); } }).Start(); i = 20; lst.Insert(0, "xx"); xx = 100;};try{ TransactionOptions tr = new TransactionOptions() { IsolationLevel = IsolationLevel.Serializable, Timeout = TransactionManager.MaximumTimeout }; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, tr)) { doSth(); scope.Complete(); }}catch (Exception ex){ Console.WriteLine("exception happens");}Console.WriteLine("i: {0}, xx: {1}", i, xx);
上面的代码,由于lst一直为null,当执行到lst.Insert的时候,会出现异常,触发事务回滚。
测试结论:回滚效果,同步SQL里面的操作回滚了,但内存中的object并未回滚,异步的SQL里面也未回滚.
如图: