我有一个长时间运行的操作,我在后台线程中执行.由于操作要么成功完成还是根本不成功,我将整个操作包装在一个事务中.
在此期间,UI的各方面需要对数据库的只读访问.为了避免阻止UI,我正在尝试在后台操作的主循环中插入对db.yieldIfContendedSafely()的调用.
这样做我想要的是UI不再被阻止,但是如果这样做有可能导致数据完整性丢失,那么我并不完全清楚.
yieldIfContendedSafely()的javadoc说:
Temporarily end the transaction to let other threads run. The
transaction is assumed to be successful so far. Do not call
setTransactionSuccessful before calling this. When this returns a new
transaction will have been created but not marked as successful. This
assumes that there are no nested transactions (beginTransaction has
only been called once) and will throw an exception if that is not the
case.
这是否意味着我的长时间运行实际上是在单独的块中提交给数据库,还是整个事务保持足够的状态以在最后一次提交整个数据,从而保持数据完整性?
解决方法:
Does this mean that my long-running operation is actually being committed to the database in separate chunks
是.在yieldIfContendedSafely()中,Android调用setTransactionSuccessful(),endTransaction(),并开始一个新事务 – 在流程中提交您的语句.没有机制在结束后回滚“真实”事务.
仅当另一个线程在数据库上等待时才会发生此行为,否则yieldIfContendedSafely()不执行任何操作.
我用以下方案检查了这一点.我启动了两个线程:一个使用事务将数据插入表中,另一个从同一个表中读取数据.事务没有调用setTransactionSuccessful()所以通常一切都在最后回滚,使表空.我添加了对yieldIfContendedSafely()的调用,之后该表不为空并且具有来自事务的数据.
原文地址:https://codeday.me/bug/20190609/1208191.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。