2 AsyncTasks可以共享同一个SQLiteDatabase对象吗? [英] Can two AsyncTasks share the same SQLiteDatabase object?

查看:90
本文介绍了2 AsyncTasks可以共享同一个SQLiteDatabase对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果他们只在其上执行查询?是这样的:

 私人SQLiteDatabase分贝;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    DB = getWritableDatabse();
}私人任务1扩展的AsyncTask<太虚,太虚,太虚> {
    @覆盖
    保护无效doInBackground(虚空......为arg0){
        db.query(DoSomething的);
        ...
    }
}私人任务2扩展的AsyncTask<太虚,太虚,太虚> {
    @覆盖
    保护无效doInBackground(虚空......为arg0){
        db.query(DoSomething的);
        ...
    }
}


解决方案

所有的应用程序应该使用相同的数据库对象的线程 - 即便同时读取和写入。 SQLite的处理与此相应的内部锁定机制。

您的有什么不的想要做的是使用多个数据库对象读取并从数据库中写入。这可能会导致数据不一致。

在这里看到:

最后一个环节是一个很好的一个。引述凯文·加利根:


  

      
  • sqlite的需要文件级锁定的照顾。许多线程可以读,可以写。该锁prevent多个写作。

  •   
  • 的Andr​​oid实现了SQLiteDatabase一些Java的锁定,以帮助保持平直。

  •   
  • 如果你去疯了,从锤数据库许多线程,数据库将(或应该)不被破坏。

  •   

  
  

下面是缺少了什么。如果您尝试写从在同一时间不同的实际连接数据库,一会失败。它不会等到第一个完成,然后写。它根本不会写你的变化。更糟的是,如果你不叫插入/更新的正确版本的SQLiteDatabase,你不会得到一个异常。你只是在你的LogCat中得到一个消息,这将是它。


顺便说一句,凯文做的 ORMLite ,我的Java ORM包了Android方工作的一个好一点的支持Android。

If they only perform queries on it? Something like:

private SQLiteDatabase db;

@Override
public void onCreate(Bundle savedInstanceState) {
    db = getWritableDatabse();
}

private Task1 extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... arg0) {
        db.query(doSomething);
        ...
    }
}

private Task2 extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... arg0) {
        db.query(doSomething);
        ...
    }
}

解决方案

All of your threads in your application should use the same database object -- even if reading and writing simultaneously. SQLite handles this with internal locking mechanisms appropriately.

What you don't want to do is to use multiple database objects to read and write from a database. That may result in inconsistent data.

See here:

The last link is a good one. To quote Kevin Galligan:

  • Sqlite takes care of the file level locking. Many threads can read, one can write. The locks prevent more than one writing.
  • Android implements some java locking in SQLiteDatabase to help keep things straight.
  • If you go crazy and hammer the database from many threads, your database will (or should) not be corrupted.

Here’s what’s missing. If you try to write to the database from actual distinct connections at the same time, one will fail. It will not wait till the first is done and then write. It will simply not write your change. Worse, if you don’t call the right version of insert/update on the SQLiteDatabase, you won’t get an exception. You’ll just get a message in your LogCat, and that will be it.

As an aside, Kevin has done a good bit of the work of the Android side of ORMLite, my Java ORM package that supports Android.

这篇关于2 AsyncTasks可以共享同一个SQLiteDatabase对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆