1

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

  • 表 A 将插入其中。
  • 用户按下按钮运行计划作业,将数据库中的数据同步到 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.");
            }
        };

有没有人遇到过这样的问题,即 Read 导致锁定?根据您的经验,我有什么可以补充的吗?这对我们来说是一个巨大的障碍,我们真的不知道为什么会这样。

4

1 回答 1

0

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

于 2019-10-02T10:27:47.100 回答