ASP.NET中TransactionScope的问题

时间:2011-05-05 15:49:58

标签: 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();
        }
    }

2 个答案:

答案 0 :(得分:5)

尝试更改构造函数。

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

答案 1 :(得分:3)

我做了一个在事务范围

上创建Max Timeout值的方法
public static TransactionScope CreateDefaultTransactionScope(TransactionScopeOption option = TransactionScopeOption.Required)
    {
        var transactionOptions = new TransactionOptions();
        transactionOptions.Timeout = TimeSpan.MaxValue;
        transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted;
        return new TransactionScope(option, transactionOptions);
    }

然后你会用它:

using (TransactionScope transaction = TransactionHelper.CreateDefaultTransactionScope())