SQLite数据库读取锁定

问题描述 投票:0回答:1

我们正在构建数据库锁定的Xamarin.Android应用程序时遇到问题。作为应用程序功能的概述:

  • 表A get插入其中。
  • 用户按下按钮以运行预定作业,以将数据从数据库同步到API。成功返回响应后,我们将删除表中的该行。
  • 用户仍然可以作为例程的一部分向表A添加数据。
  • 我们在表A中获得了锁。

我们构建了一个测试应用程序,以尝试通过构建表B来复制表A中的数据的解决方案进行模拟,以便用户可以继续使用表A。但是当表B上的数据试图进行同步时(删除是否有模拟它的数据的方法,我们仍然在Get()上的表上获得锁。

我的数据库代码在这里:

using System;
using SQLite;
using System.Collections.Generic;
using System.Linq;

namespace LockSimulation
{
    public class SampleDatabaseB : IDatabase
    {
        public SampleDatabaseB()
        {
        try
        {
            string dbPath = System.IO.Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.Personal),
                "sampleb.db3");

            using (SQLiteConnection db = new SQLiteConnection(dbPath))
            {
                db.CreateTable<Sample>();
                db.Close();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("DB already created");
        }

    }


    public List<Sample> Get()
    {
        List<Sample> samples = new List<Sample>();
        string dbPath = System.IO.Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.Personal),
                "sampleb.db3");

        using (var db = new SQLiteConnection(dbPath,SQLiteOpenFlags.ReadOnly))
        {

            var s = db.Table<Sample>();

            // ISSUE IS HERE> s.ToList() SHOWS THE LOCK

            samples = s.ToList();
            db.Close();

        }
        return samples;
    }

    public void Copy(List<Sample> samples)
    {
        string dbPath = System.IO.Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.Personal),
                "sampleb.db3");

        using (var db = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache))
        {
            db.InsertAll(samples);
            db.Close();
        }
    }

    public void Save(object sample)
    {
        string dbPath = System.IO.Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.Personal),
                "sampleb.db3");

        using (var db = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache))
        {
            db.Insert(sample);
            db.Close();
        }
    }
  }
}

我的预定作业在这里:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Android.App;
using Android.App.Job;

namespace LockSimulation
{
    [Service(Name = "com.testapp.LockSimulation.Job", Permission = "android.permission.BIND_JOB_SERVICE")]
public class SyncJob : JobService
{
    SampleDatabaseB db = null;

    public override bool OnStartJob(JobParameters jobParams)
    {
        db = new SampleDatabaseB();
        Task.Run( () =>
        {
            var loopCount = jobParams.Extras.GetInt("LoopCount", 10);
            List<Sample> samples = db.Get();
            try
            {
                foreach (Sample sample in samples)
                {
                    db.Delete(sample);
                }

                if (db.Get().Count == 0)
                {
                    JobFinished(jobParams, false);
                }
                else
                {
                    JobFinished(jobParams, true);
                }
            }
            catch (SQLite.SQLiteException ex)
            {
                Console.WriteLine(ex);
            }
        });

        return true;
    }

    public override bool OnStopJob(JobParameters jobParams)
    {
        //Before the Job tries to finish, we will check the Samples DB.
        //If there is Samples on the DB, we will need to tell the process 
        //to run the job again.
        //If there is an issues in doing so, tell the process to try again.

        //if (db.Get().Count == 0)
        //{
        //    return false;
        //}
        //else
        //{
        //    return true;
        //}

        try
        {
            if (db.Get().Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        catch (Exception ex)
        {
            var properties = new Dictionary<string, string>
            {
                { "Syncing Job Exception", ex.Message},
                { "DB Issue", "DB could be having processing done on it. Will try again."}
            };
            Console.WriteLine(properties);
            //Crashes.TrackError(ex, properties);
            return true;
        }
    }
}
}

我的按钮代码在这里:

button.Click += delegate {
            SampleDatabaseB sampleDatabaseB = new SampleDatabaseB();

            List<Sample> samplesA = sampleDatabase.Get();
            List<Sample> samplesB = sampleDatabaseB.Get();

            Console.WriteLine(String.Format("Total Samples In A Before Copy {0}", samplesA.Count));
            Console.WriteLine(String.Format("Total Samples In B Before Copy {0}", samplesB.Count));

            sampleDatabaseB.Copy(samplesA);
            sampleDatabase.DeleteAll();

            Console.WriteLine(String.Format("Total Samples In B After Copy {0}", sampleDatabaseB.Get().Count));

            Console.WriteLine(String.Format("Total Samples In A After Copy {0}", sampleDatabase.Get().Count));


            var jobBuilder = this.CreateJobBuilderUsingJobId<SyncJob>(1)
                                     .SetRequiredNetworkType(NetworkType.Any)
                                     .SetBackoffCriteria(2000, BackoffPolicy.Linear)
                                     .SetPersisted(true)
                                     .Build();

            var jobScheduler = (JobScheduler)GetSystemService(JobSchedulerService);
            var scheduleResult = jobScheduler.Schedule(jobBuilder);

            if (JobScheduler.ResultSuccess == scheduleResult)
            {
                Console.WriteLine("Samples Scheduled for Syncing Successfully");
            }
            else
            {
                Console.WriteLine("Samples Unsuccessfully Scheduled for Syncing.");
            }
        };

有人在读取引起锁定时遇到这样的问题吗?根据您的经验,我有什么可以补充的吗?对我们来说,这是一个巨大的障碍,我们真的不知道为什么会发生。

android sqlite xamarin.android sqlite-net-pcl
1个回答
0
投票

我在本机android中也遇到了类似的问题。我正在尝试做某事,然后关闭桌子并再次打开。我一直得到android.database.sqlite.SQLiteDatabaseLockedException: database is locked (code 5)。我设法不一直打开和关闭数据库来解决它。

© www.soinside.com 2019 - 2024. All rights reserved.