大家好,又见面了,我是你们的朋友全栈君。
今天在调试代码的时候遇到一个这样的错误:
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(); } }
转载于:https://www.cnblogs.com/lvjianwei/p/5177447.html
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/161941.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...