我有10000条记录要插入SQLite数据库使用多线程。使用多线程在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','[email protected]','M',1)";
SQLiteCommand command = new SQLiteCommand(sqlInsert, sqliteConn);
command.ExecuteNonQuery();
sqliteConn.Close();
}
}
}
在高于逻辑记录在数据库正确插入,但它是采取> = 25分钟到插入10000分的记录。
当我在一分钟内检查了大约300到400条记录插入。
我也用Transaction
插入记录,但没有性能提高
有没有什么办法让我可以能提高性能?
SQLite
如何在Multithreading
内部工作?
你检查了这个:https://stackoverflow.com/questions/3852068/sqlite-insert-very-slow? – Piotr
您应该在单个连接和单个事务中执行所有1000次插入,以便事务有任何效果。你是否有理由在多个线程中做这件事?在单个事务中插入所有10000条记录可能会更快。 –
您是否比较了在单线程中完成此操作所需的时间?并发智能SQLite是多重读取但是是单写的。 –