我有 10000 条记录要使用多线程插入到 SQLite 数据库中。
private void btnThread_Click(object sender, EventArgs e)
{
Thread th1 = new Thread(new ThreadStart(Save1));
Thread th2 = new Thread(new ThreadStart(Save2));
Thread th3 = new Thread(new ThreadStart(Save3));
Thread th4 = new Thread(new ThreadStart(Save4));
Thread th5 = new Thread(new ThreadStart(Save5));
Thread th6 = new Thread(new ThreadStart(Save6));
Thread th7 = new Thread(new ThreadStart(Save7));
Thread th8 = new Thread(new ThreadStart(Save8));
Thread th9 = new Thread(new ThreadStart(Save9));
Thread th10 = new Thread(new ThreadStart(Save10));
th1.Start();
th2.Start();
th3.Start();
th4.Start();
th5.Start();
th6.Start();
th7.Start();
th8.Start();
th9.Start();
th10.Start();
}
在上面的代码中,每个线程调用一个函数来保存记录,如下所示
private void Save1()
{
for(int i = 0; i < 1000; i++)
{
using(SQLiteConnection sqliteConn = new SQLiteConnection("Data Source='" + dbPath + "'"))
{
sqliteConn.Open();
string date = DateTime.Now.ToString();
string sqlInsert = "insert into PatientDetail (Name, Age, Date, PhoneNumber, Email, PatientSex, Status ) values ('Patient Name1', 35,'" + date + "','9856235674','patient@gmail.com','M',1)";
SQLiteCommand command = new SQLiteCommand(sqlInsert, sqliteConn);
command.ExecuteNonQuery();
sqliteConn.Close();
}
}
}
在上面的逻辑记录中正确插入数据库,但插入 10000 条记录需要 >=25 分钟。
当我在一分钟内检查了大约 300 到 400 条记录插入时。
我也使用 Transaction
插入记录,但性能没有提高
有什么方法可以提高性能吗?
SQLite
如何在多线程
中工作?
最佳答案
This article on SQLite.org describes SQLite's thread safety mechanisms and modes .默认情况下,SQLite 确保序列化所有操作(序列化是一次不做不止一件事,而不是序列化对象),因此它是线程安全的,但可以取消这种模式。
插入 1000 条记录最好在单个事务中完成,即使您不在单个事务中执行此操作,也可以通过不每次都打开新连接来更快。但是,如果您的代码试图模拟从单独的代码片段中一条一条地插入 1000 条记录而不是对它们进行批处理的性能,那么您在测试中获得的性能就代表了这一点。
让 10 个线程竞争执行此插入是问题的一部分,但不是全部问题。如果您有 10 个线程,每个线程一个接一个地插入 1000 个插入,那么 SQLite 必须序列化 10000 个操作。引入某种批处理可以解决这个问题,并且还可以让您使用事务,这本身会极大地提升性能。
关于c# - 使用多线程在 SQLite 数据库中插入记录的性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45481819/