Skip to main content
 首页 » 编程设计

C# + SQLite之数据库锁

2024年01月28日33unruledboy

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

我的问题是有时缓存操作与其他线程的操作冲突。

任何人都可以帮助我或如何解决这个困境?

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

请您参考如下方法:

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

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

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

顺便说一句,您不应该使用数据库级别的事务而不是应用程序级别吗?类似于 http://msdn.microsoft.com/en-us/library/86773566.aspx

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); 
        } 
    } 
}