我有一些按预期工作的代码。
public class PlayCommand: IPlayCommand {
// this code works but `_userService.GetById()` and `_userService.Save()` lock the UI.
public void Execute(object parameter) {
var vm = (HomeFragmentViewModel) parameter;
// first hit on the database
var user = _userService.GetById(Mvx.Resolve < UserModel > ().Id);
user.PlayPositions.First(p = > p.ChapterId == vm.UserPlayPosition.ChapterId).PlayPosition = _audioPlayer.CurrentPosition;
// second hit on the database.
_userService.Save(user);
}
}
我遇到的问题是,如果我尝试从UI层卸载工作以加快性能,则用户不会得到保存。
// Even though I can see all lines executing, the database doesn't get updated
// when using this approach.
public void Execute(object parameter) {
var vm = (HomeFragmentViewModel)parameter;
ThreadPool.QueueUserWorkItem(o = > UpdateUserPlayPosition(vm));
// also tried
// new Task(() => UpdateUsersCurrentChapter(vm)).Start();
}
private void UpdateUserPlayPosition(HomeFragmentViewModel vm)
{
var user = _userService.GetById(Mvx.Resolve<UserModel>().Id);
user.PlayPositions.First(p => p.ChapterId == vm.UserPlayPosition.ChapterId).PlayPosition = _audioPlayer.CurrentPosition;
// execute a new task to save the user back to the local database
_userService.Save(user);
}
下次我向数据库询问CurrentPosition
时,它仍然设置为原始值(0)。
我还注意到调试输出中有很多以下内容。
01-13 13:31:57.242 E/SQLiteLog(16542): (1) statement aborts at 2: [ROLLBACK] cannot rollback - no transaction is active
我确实尝试在我的ConnectionProvider的构造函数中的配置中将SQLite设置为MultiThread,但是当我第一次尝试命中数据库时它会抛出一个不同的异常。
public class DbConnectionProvider : IDbConnectionProvider
{
private readonly string _connectionString;
public DbConnectionProvider(string sqliteDatabasePath)
{
_connectionString = "Data Source=" + sqliteDatabasePath;
SqliteConnection.SetConfig(SQLiteConfig.MultiThread);
}
public SqliteConnection GetOpenConnection()
{
var connection = new SqliteConnection(_connectionString);
if (connection == null) throw new Exception("Could not create a database connection.");
connection.Open();
return connection;
}
}
01-18 13:33:31.278 E/mono (21714): System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Mono.Data.Sqlite.SqliteException: Library used incorrectly
01-18 13:33:31.278 E/mono (21714): at Mono.Data.Sqlite.SqliteConnection.SetConfig (SQLiteConfig config) [0x00000] in <filename unknown>:0
我正在使用Mono.Data.Sqlite
v2.0.5.0 作为我的DbProvider的后端。