多线程应用程序中的SQLite“数据库已锁定”错误

use*_*808 5 c# sqlite nhibernate multithreading locking

有一个多线程应用程序,可以处理较大的DB文件(> 600 Mb)。当我添加Blob数据时开始出现“数据库已锁定”问题,并且每个请求开始使用大于30 Kb的BLOB数据进行操作。我认为问题与小硬盘速度有关。看起来SQLite删除了-journal文件,我的应用程序的一个线程失锁了(因为-journal文件已被应用并删除了),而我的其他线程想对数据库进行处理,但是SQLite仍在更新DB文件...当然,我可以在每次DB调用后延迟一分钟,但这不是解决方案,因为我需要更快的速度。

现在,我使用每个会话(每个线程)实现的会话。因此,每个应用程序对象有一个ISessionFactory,而许多ISession对象是。

有我的帮助程序类(如您所见,我使用IsolationLevel.Serializable和CurrentSessionContext = ThreadStaticSessionContext):

public abstract class nHibernateHelper
{
    private static FluentConfiguration _configuration;
    private static IPersistenceContext _persistenceContext;

    static nHibernateHelper() {}

    private static FluentConfiguration ConfigurePersistenceLayer()
    {
        return Fluently.Configure().Database(FluentNHibernate.Cfg.Db.SQLiteConfiguration.Standard.ShowSql().UsingFile(_fileName).IsolationLevel(IsolationLevel.Serializable).MaxFetchDepth(2)).
                Mappings(m => m.FluentMappings.AddFromAssemblyOf<Foo>()).CurrentSessionContext(typeof(ThreadStaticSessionContext).FullName);
    }

    public static ISession CurrentSession
    {
        get { return _persistenceContext.CurrentSession; }
    }

    public static IDisposable OpenConnection()
    {
        return new DbSession(_persistenceContext);
    }
}

public class PersistenceContext : IPersistenceContext, IDisposable
{
    private readonly FluentConfiguration _configuration;
    private readonly ISessionFactory _sessionFactory;

    public PersistenceContext(FluentConfiguration configuration)
    {
        _configuration = configuration;
        _sessionFactory = _configuration.BuildSessionFactory();
    }

    public FluentConfiguration Configuration { get { return _configuration; } }
    public ISessionFactory SessionFactory { get { return _sessionFactory; } }

    public ISession CurrentSession
    {
        get
        {
            if (!CurrentSessionContext.HasBind(SessionFactory))
            {
                OnContextualSessionIsNotFound();
            }
            var contextualSession = SessionFactory.GetCurrentSession();
            if (contextualSession == null)
            {
                OnContextualSessionIsNotFound();
            }
            return contextualSession;
        }
    }

    public void Dispose()
    {
        SessionFactory.Dispose();
    }

    private static void OnContextualSessionIsNotFound()
    {
        throw new InvalidOperationException("Ambient instance of contextual session is not found. Open the db session before.");
    }

}

public class DbSession : IDisposable
{
    private readonly ISessionFactory _sessionFactory;

    public DbSession(IPersistenceContext persistentContext)
    {
        _sessionFactory = persistentContext.SessionFactory;
        CurrentSessionContext.Bind(_sessionFactory.OpenSession());
    }

    public void Dispose()
    {
        var session = CurrentSessionContext.Unbind(_sessionFactory);
        if (session != null && session.IsOpen)
        {
            try
            {
                if (session.Transaction != null && session.Transaction.IsActive)
                {
                    session.Transaction.Rollback();
                }
            }
            finally
            {
                session.Dispose();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并且有存储库帮助程序类。如您所见,每个数据库调用都有锁,因此对于不同的线程,并发数据库调用也不会出现,因为_locker对象是静态的。

public abstract class BaseEntityRepository<T, TId> : IBaseEntityRepository<T, TId> where T : BaseEntity<TId>
{
    private ITransaction _transaction;
    protected static readonly object _locker = new object();

    public bool Save(T item)
    {
        bool result = false;

        if ((item != null) && (item.IsTransient()))
        {
            lock (_locker)
            {
                try
                {
                    _transaction = session.BeginTransaction();
                    nHibernateHelper.CurrentSession.Save(item);
                    nHibernateHelper.Flush();
                    _transaction.Commit();          
                    result = true;
                } catch 
                {
                    _transaction.Rollback();
                    throw;
                }
                //DelayAfterProcess();
            }
        }
        return result;
    }

    //same for delete and update 

    public T Get(TId itemId)
    {
        T result = default(T);

        lock (_locker)
        {
            try
            {
                result = nHibernateHelper.CurrentSession.Get<T>(itemId);
            }
            catch 
            {
                throw;
            }
        }
        return result;
    }

    public IList<T> Find(Expression<Func<T, bool>> predicate)
    {
        IList<T> result = new List<T>();
        lock (_locker)
        {
            try
            {
                result = nHibernateHelper.CurrentSession.Query<T>().Where(predicate).ToList();
            }
            catch 
            {
                throw;
            }
        }
        return result;
    }


}
Run Code Online (Sandbox Code Playgroud)

我使用这样的以前的类(每个线程一次调用nHibernateHelper.OpenConnection())。存储库通过单调实例化:

using (nHibernateHelper.OpenConnection())
{
    Foo foo = new Foo();
    FooRepository.Instance.Save(foo);
}    
Run Code Online (Sandbox Code Playgroud)

我试图将IsolationLevel更改为ReadCommited,但这不会改变问题。我也尝试通过将SQLite日志模式从日志更改为WAL来解决此问题:

using (nHibernateHelper.OpenConnection()) 
{
    using (IDbCommand command = nHibernateHelper.CurrentSession.Connection.CreateCommand())
    {
        command.CommandText = "PRAGMA journal_mode=WAL";
        command.ExecuteNonQuery();
    }
}
Run Code Online (Sandbox Code Playgroud)

这在具有快速HDD的计算机上有所帮助,但是在某些情况下我遇到了相同的错误。然后,我尝试向存储库添加“数据库更新文件存在”检查,并在每次保存/更新/删除过程之后延迟:

    protected static int _delayAfterInSeconds = 1;
    protected void DelayAfterProcess()
    {
        bool dbUpdateInProcess = false;
        do
        {
            string fileMask = "*-wal*";
            string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), fileMask);
            if ((files != null) && (files.Length > 0))
            {
                dbUpdateInProcess = true;
                Thread.Sleep(1000);
            }
            else
            {
                dbUpdateInProcess = false;
            }
        } while (dbUpdateInProcess);
        if (_delayAfterInSeconds > 0)
        {
            Thread.Sleep(_delayAfterInSeconds * 1000);
        }
    }
Run Code Online (Sandbox Code Playgroud)

-journal文件无法使用相同的解决方案(检查数据库更新文件)。它报告说-journal文件已删除,但是我仍然遇到错误。对于-wal文件,它可以正常工作(我认为。我需要更多时间对其进行测试)。但是这种解决方案严重制动了程序。

也许你可以帮我吗?

use*_*808 5

回答我自己。问题与 .IsolationLevel(IsolationLevel. Serializable ) 有关。当我改变了这一行.IsolationLevel(IsolationLevel将。READCOMMITTED)的问题消失了。