zoukankan      html  css  js  c++  java
  • TransactionScope TransactionAbortedException

    今天在调试代码的时候遇到一个这样的错误:

    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();
                }
            }
  • 相关阅读:
    Oracle查看表或者视图的定义语句
    SpringMvc使用FastJson做为json的转换器(注解方式)
    Centos7安装vsftpd
    linux下的find文件查找命令与grep文件内容查找命令
    Centos7虚拟机下配置静态IP
    替换Jar包内的文件
    Java 获取本机IP地址
    RecyclerView 与 ItemTouchHelper 实现拖拽效果
    Android 开发日常积累
    Android 自定义 View 知识点
  • 原文地址:https://www.cnblogs.com/lvjianwei/p/5177447.html
Copyright © 2011-2022 走看看