首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# + SQLite -数据库锁

C# + SQLite -数据库锁
EN

Stack Overflow用户
提问于 2013-10-03 12:54:53
回答 2查看 5K关注 0票数 1

我的应用程序出现问题。它是一个桌面应用程序,由c#和用于缓存的Sqlite DB组成,并且是多线程的。

我的问题是caching operation有时会与来自另一个线程的操作冲突。

有谁可以帮助我或者如何解决这个难题?

我正在考虑解锁数据库(也许重启程序),但我知道这不是一个好方法。

EN

回答 2

Stack Overflow用户

发布于 2013-10-03 17:15:48

因此,对于类似的问题,共识似乎是您需要自己进行锁定。一些回答指向将相同的SqliteConnection对象传递给执行写入的所有线程。尽管我不认为这会解决问题。

我建议重新考虑并发写/读。我假设你的线程做了一些工作,然后保存到那个线程中的数据库中。我会重写它,让线程做一些工作并返回输出。将数据保存到db的过程不需要与执行工作的过程耦合。并发读取应该在没有更改的情况下工作,因为该锁是用于读取的shared锁。当然,可能会有写入和读取同时发生的情况。在这种情况下,错误将再次弹出。

我认为使用全局lock object并使用它来同步/序列化所有的写/读可能会更简单。然而,当你这样做的时候,你已经有效地使数据库访问成为单线程的。这是一个问题,答案取决于你的最终目标是什么。

顺便说一句,你不应该使用数据库级别的事务而不是应用程序级别的事务吗?像http://msdn.microsoft.com/en-us/library/86773566.aspx这样的东西

代码语言:javascript
复制
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    SqlCommand command = connection.CreateCommand();
    SqlTransaction transaction;

    // Start a local transaction.
    transaction = connection.BeginTransaction("SampleTransaction");

    // Must assign both transaction object and connection 
    // to Command object for a pending local transaction
    command.Connection = connection;
    command.Transaction = transaction;

    try
    {
        command.CommandText =
            "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
        command.ExecuteNonQuery();
        command.CommandText =
            "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
        command.ExecuteNonQuery();

        // Attempt to commit the transaction.
        transaction.Commit();
        Console.WriteLine("Both records are written to database.");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
        Console.WriteLine("  Message: {0}", ex.Message);

        // Attempt to roll back the transaction. 
        try
        {
            transaction.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);
        }
    }
}
票数 5
EN

Stack Overflow用户

发布于 2013-10-03 15:30:29

我也想做同样的事情,将SQLiteDatabase链接到C#应用程序。我得到了:

Database is locked(5)

另外,我在代码中使用Transactions修复了这个问题,下面是我使用的一个事务的示例:

代码语言:javascript
复制
 using (TransactionScope tran = new TransactionScope())
 {
     //Perform action on SQLite Database here.


     tran.Complete();
 }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19151062

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档