加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql-server – ZombieCheck异常 – 此SqlTransaction已完成;它不

发布时间:2020-12-12 08:30:06 所属栏目:MsSql教程 来源:网络整理
导读:我有以下代码执行单个行到数据库表的提交(SQL 2008 / .NET 4) using (var db = new MyDbDataContext(_dbConnectionString)){ Action action = new Action(); db.Actions.InsertOnSubmit(dbAction); db.SubmitChanges();} 通常一切都很好,但有一段时间我会得到
我有以下代码执行单个行到数据库表的提交(SQL 2008 / .NET 4)
using (var db = new MyDbDataContext(_dbConnectionString))
{
    Action action = new Action();
    db.Actions.InsertOnSubmit(dbAction);
    db.SubmitChanges();
}

通常一切都很好,但有一段时间我会得到以下例外:

System.InvalidOperationException: This SqlTransaction has completed; it is no longer usable.
at System.Data.SqlClient.SqlTransaction.ZombieCheck()
at System.Data.SqlClient.SqlTransaction.Rollback()
at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)

在SO上有一些类似的问题,但是在阅读之后,我无法解决问题.

这可能是由于SQL超时(在调用完成后接近25秒发生异常)?或者我应该期望在这种情况下的SQL超时异常?

有人知道还有什么可能造成这种情况吗?

解决方法

DataContext.SubmitChanges方法在其主体中具有以下代码行:
// ...
try
{
    if (this.provider.Connection.State == ConnectionState.Open)
    {
        this.provider.ClearConnection();
    }
    if (this.provider.Connection.State == ConnectionState.Closed)
    {
        this.provider.Connection.Open();
        flag = true;
    }
    dbTransaction = this.provider.Connection.BeginTransaction(IsolationLevel.ReadCommitted);
    this.provider.Transaction = dbTransaction;
    new ChangeProcessor(this.services,this).SubmitChanges(failureMode);
    this.AcceptChanges();
    this.provider.ClearConnection();
    dbTransaction.Commit();
}
catch
{
    if (dbTransaction != null)
    {
        dbTransaction.Rollback();
    }
    throw;
}
// ...

当连接超时时,执行catch块,并且dbTransaction.Rollback();行将抛出一个InvalidOperationException.

如果您可以控制代码,可以像下面那样捕获异常:

catch
{
    // Attempt to roll back the transaction. 
    try
    {
        if (dbTransaction != null)
        {
            dbTransaction.Rollback();
        }
    }
    catch (Exception ex2)
    {
        // This catch block will handle any errors that may have occurred 
        // on the server that would cause the rollback to fail,such as 
        // a closed connection.
        Console.WriteLine("Rollback Exception Type: {0}",ex2.GetType());
        Console.WriteLine("  Message: {0}",ex2.Message);
    }
    throw;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读