我的应用程序出现问题。它是一个桌面应用程序,由c#和用于缓存的Sqlite DB组成,并且是多线程的。
我的问题是caching operation有时会与来自另一个线程的操作冲突。
有谁可以帮助我或者如何解决这个难题?
我正在考虑解锁数据库(也许重启程序),但我知道这不是一个好方法。
发布于 2013-10-03 17:15:48
因此,对于类似的问题,共识似乎是您需要自己进行锁定。一些回答指向将相同的SqliteConnection对象传递给执行写入的所有线程。尽管我不认为这会解决问题。
我建议重新考虑并发写/读。我假设你的线程做了一些工作,然后保存到那个线程中的数据库中。我会重写它,让线程做一些工作并返回输出。将数据保存到db的过程不需要与执行工作的过程耦合。并发读取应该在没有更改的情况下工作,因为该锁是用于读取的shared锁。当然,可能会有写入和读取同时发生的情况。在这种情况下,错误将再次弹出。
我认为使用全局lock object并使用它来同步/序列化所有的写/读可能会更简单。然而,当你这样做的时候,你已经有效地使数据库访问成为单线程的。这是一个问题,答案取决于你的最终目标是什么。
顺便说一句,你不应该使用数据库级别的事务而不是应用程序级别的事务吗?像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);
}
}
}发布于 2013-10-03 15:30:29
我也想做同样的事情,将SQLiteDatabase链接到C#应用程序。我得到了:
Database is locked(5)
另外,我在代码中使用Transactions修复了这个问题,下面是我使用的一个事务的示例:
using (TransactionScope tran = new TransactionScope())
{
//Perform action on SQLite Database here.
tran.Complete();
}https://stackoverflow.com/questions/19151062
复制相似问题