我的程序由许多类组成,它们运行自己的更新功能来检查 sqlite 数据库并在发现更改时进行更新。
Async Function update() As Task(Of String)
.
.
Await Task.Run(Sub()
.
.
End Sub)
.
.
helper.updatedb(par1, par2, par3, par4)
.
.
End Function
Sub updatedb(ByVal name As String, ByVal entry As String, ByVal smth As String, Optional ByVal random As String = vbNullString)
Dim SQLconnect As New SQLite.SQLiteConnection()
Dim SQLcommand As SQLiteCommand
SQLconnect.ConnectionString = "data source=" + dbpath
SQLconnect.Open()
SQLcommand = SQLconnect.CreateCommand
SQLcommand.CommandText = "SELECT ""entry"" FROM profiles WHERE ""name"" = @name"
SQLcommand.Parameters.AddWithValue("@name", LCase(name))
Dim SQLreader As SQLiteDataReader = SQLcommand.ExecuteReader()
SQLreader.Read()
Dim result As String = SQLreader(0)
SQLcommand.Dispose()
SQLcommand = SQLconnect.CreateCommand
SQLcommand.CommandText = "UPDATE profiles SET ""entry"" = @entry WHERE ""name"" = @name"
SQLcommand.Parameters.AddWithValue("@name", LCase(name))
SQLcommand.Parameters.AddWithValue("@entry", entry)
SQLcommand.ExecuteNonQuery()
SQLcommand.Dispose()
SQLreader.Close()
SQLconnect.Close()
SQLconnect.Dispose()
End Sub
当执行 SQLcommand.ExecuteNonQuery 而另一个线程可能对数据库具有写访问权限时,就会出现问题。“System.Data.SQLite.dll 中发生了‘System.Data.SQLite.SQLiteException’类型的第一次机会异常”。
我在其他一些线程中读到,这可以在更新命令上使用互斥锁来解决。我将如何在我的代码中实现互斥锁?是否有一些有利于可移植性并且没有此类并发问题的 sqlite 替代方案?