线程、流畅的nhibernate和保存数据都会导致死锁

本文关键字:数据 死锁 保存 nhibernate 线程 | 更新日期: 2023-09-27 18:22:06

我使用C#线程处理和解析一些数据,当我试图用fluent nhibernate保存和提交这些数据时,我会出现死锁。默认情况下提交线程是否安全?如何防止这里出现死锁?

//problem and where i get deadlock
advertismentsDao.Save(ad);
advertismentsDao.CommitChanges();
public T Save(T entity)
{
    NHibernateSession.Save(entity);
    return entity;
}
public void CommitChanges()
{
    if (NHibernateSessionManager.Instance.HasOpenTransactionOn(SessionFactoryConfigPath))
    {
        NHibernateSessionManager.Instance.CommitTransactionOn(SessionFactoryConfigPath);
    }
    else
    {
        // If there's no transaction, just flush the changesslate
        NHibernateSessionManager.Instance.GetSessionFrom(SessionFactoryConfigPath).Flush();
    }
}

和错误:

Transaction (Process ID 78) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
StackTrace:    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
   at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd)
   at NHibernate.Id.IdentityGenerator.InsertSelectDelegate.ExecuteAndExtract(IDbCommand insert, ISessionImplementor session)
   at NHibernate.Id.Insert.AbstractReturningDelegate.PerformInsert(SqlCommandInfo insertSQL, ISessionImplementor session, IBinder binder)

线程、流畅的nhibernate和保存数据都会导致死锁

这是SQL死锁,而不是多线程