我构建了一个类来同步两个不同数据源之间的数据。这种同步分为多个部分(和方法)。每个方法都有自己的 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/