今天在调试代码的时候遇到一个这样的错误:
System.Transactions.TransactionAbortedException was caught
HResult=-2146233087
Message=The transaction has aborted.
Source=System.Transactions
查了一下原因,主要是由于嵌套事务中,底层事务没有关闭,然后上层继续使用导致的,不过前提是TransactionScope中使用的是TransactionScopeOption.Required
代码示例:
public void TransactionScopeTest() { using(TransactionScope ts=new TransactionScope(TransactionScopeOption.Required)) { //do something using(TransactionScope tsa=new TransactionScope(TransactionScopeOption.Required)) { //do A tsa.Complete(); } using (TransactionScope tsb = new TransactionScope(TransactionScopeOption.Required)) { //do B tsb.Complete(); } ts.Complete(); } }
上述代码时一个TransactionScope内嵌两个TransactionScope,如果tsa.Complete()没有执行,
那么在using (TransactionScope tsb = new TransactionScope(TransactionScopeOption.Required))就会抛出TransactionAbortedException异常:The transaction has aborted
所以在使用TransactionScope的时候要注意,嵌套使用的时候,如果出现问题需要尽快的抛出,而不是任由其继续走下去,比如:
public void TransactionScopeTest() { using(TransactionScope ts=new TransactionScope(TransactionScopeOption.Required)) { //do something bool isASuccess = true; using(TransactionScope tsa=new TransactionScope(TransactionScopeOption.Required)) { //do A tsa.Complete(); } if(!isASuccess) { return; } bool isBSuccess = true; using (TransactionScope tsb = new TransactionScope(TransactionScopeOption.Required)) { //do B tsb.Complete(); } if(!isBSuccess) { return; } ts.Complete(); } }