Sqlite 事务阻塞 Android ui
在我的 Android 应用程序中,有一个运行时间相对较长的 AsyncTask,我正在运行该任务以在应用程序启动时更新数据库。如果用户在任务完成之前退出应用程序,我需要将其包装在事务中以回滚。然而,由于将代码包装在事务中,它会阻塞 ui,直到任务完成。既然代码已经在单独的线程中运行,为什么会出现这种情况?
我正在使用 ORMLite,这基本上是事务的包装器,更新数据库的代码位于 call() 内部...,在添加代码以更新事务内的数据库之前,没有锁定 ui...
public ConnectionSource source;
@Override
protected Boolean doInBackground(Context... params) {
try {
TransactionManager.callInTransaction(source, new Callable<Void>() {
public Void call() throws Exception {
return null;
}
});
In my android app there is a relatively long running AsyncTask I'm running to update the database when the app starts up. I'm needing to wrap that in a transaction to roll things back if the user exits the app before the task is finished. However since wrapping the code in a transaction it is blocking the ui untill the task is complete. Why would this be since the code is already running in a separate thread?
I'm using ORMLite and this is the wrapper for the transaction basically,the code to update the db goes inside call().., before adding the code to update the db inside a transaction there was no locking of the ui...
public ConnectionSource source;
@Override
protected Boolean doInBackground(Context... params) {
try {
TransactionManager.callInTransaction(source, new Callable<Void>() {
public Void call() throws Exception {
return null;
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是,SQLite 事务是独占的,它们会阻止所有其他数据库活动。我怀疑即使您在另一个线程中,UI 线程也正在执行某种必须等待事务完成的数据库活动。
Unfortunately, SQLite transactions are exclusive and they block all other database activity. I suspect that even though you are in another thread, the UI thread is doing some sort of database activity which has to wait for the transaction to finish.
从 API 11 开始,Android 允许 WAL 模式下有一个写入线程和多个读取线程。您必须切换到 WAL 模式并使用 beginTransactionNonExclusive() 以避免阻塞读取线程。
查看我的文章,了解有关 SQLite 中 WAL 模式和并发性的更多详细信息:
http://www.skoumal.net/en/parallel-read-and-write-in-sqlite/
Since API 11 Android allows one writing thread and many reading threads in WAL mode. You have to switch to WAL mode and use beginTransactionNonExclusive() to avoid blocking reading threads.
Check my article for more details about WAL mode and concurency in SQLite:
http://www.skoumal.net/en/parallel-read-and-write-in-sqlite/