Fad*_*adz 1 c# sqlite multithreading
我面临着我的应用程序的问题.它是一个桌面应用程序,由c#和Sqlite DB组成,用于缓存,并且是多线程的.我的问题有时是缓存操作与其他线程的操作冲突.
任何人都可以帮助我或如何解决是两难?
我想解锁数据库(也许重启程序),但我知道这不是一个好方法.
对类似的问题进行搜索,似乎一致认为你需要自己进行锁定.一些答案指向将同一个SqliteConnection对象传递给执行写入的所有线程.虽然我不认为这会解决问题.
我建议重新考虑并发写/读.我假设您的线程做了一些工作,然后保存到该线程中的数据库.我会重写它,使线程做一些工作并返回输出.将数据保存到db的过程不需要与执行工作的过程相结合.并发读取应该没有变化,因为锁是一个shared读取.当然,可能存在写入和读取同时发生的情况.在这种情况下,错误会再次出现.
我认为使用全局lock object并使用它来同步/序列化所有写入/读取可能更简单.但是,在您这样做的那一刻,您已经有效地使db访问单线程.这是其中一个问题,答案取决于您的最终目标.
顺便说一下,您不应该使用数据库级事务而不是应用程序级别吗?像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);
}
}
}
Run Code Online (Sandbox Code Playgroud)