c# - ASP.NET 中 TransactionScope 的问题

标签 c# sql-server transactions transactionscope

我构建了一个类来同步两个不同数据源之间的数据。这种同步分为多个部分(和方法)。每个方法都有自己的 TransactionScope,并且方法按顺序运行。

每次运行此代码时,我都会收到以下错误消息:

“与当前连接关联的事务已完成但尚未释放。必须先释放事务才能使用连接执行 SQL 语句。”

以下代码是使用 TransactionScope 的此类方法的示例:

private void SomeMethod()
{
        try
        {
            using (var _transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
            {
                using (SqlConnection _connection = new SqlConnection(connectionstring))
                {
                    _connection.Open();

                    DoSomething()...
                }

                _transactionScope.Complete();
            }
        }
        catch (TransactionAbortedException e)
        {
            nlog.Error(string.Format("The transaction has been aborted: {0}", e.Message));
            throw e;
        }
        catch (Exception e)
        {
            throw e;
        }
}

似乎调用 "_transactionScope.Complete()" 不足以终止事务作用域。有人知道我做错了什么吗?

提前致谢!

更新 感谢您的回复。经过几次测试,我发现只有在一个方法中有多个查询时才会出现这个问题。例如:

 try
    {
        using (TransactionScope _transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
        {
            using (SqlConnection _connection = new SqlConnection(connectionstring))
            {
                _connection.Open();

                //new method:
                using (TransactionScope _transactionScope = new TransactionScope(TransactionScopeOption.Suppress))
                {
                    //a selectquery
                }

                //an update or insert query

            _transactionScope.Complete();
        }
    }

最佳答案

尝试更改构造函数。

using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required,
                new TransactionOptions()
                { 
                    IsolationLevel = System.Transactions.IsolationLevel.Serializable,
                    Timeout = TimeSpan.FromSeconds(120)
                }))

关于c# - ASP.NET 中 TransactionScope 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5900643/

相关文章:

c# - 使用惰性属性时,NHibernate 3.2 对象在刷新期间不会更新

postgresql - 没有显式锁定的postgres死锁

sql - 使用表列值之一创建额外的总和列

c# - 检查房间可用性

c# - 如何将数据表复制到SQL Server?

multithreading - 事务锁定2算法可序列化吗?

php - 使用 CURL 发布方法的 Google 翻译 API

C# 异步 Ping : not work from a Threading. 定时器

c# - Quartz.Net cron 触发器每 45 分钟安排一次工作

c# - 猴子可以走 2 步或 3 步 - 有多少种不同的方法可以到达顶峰?