sqliteandroid-sqlitesqlite-net

Sqlite sync and async together


Is it good practice to use sqlite sync and async together.

Example i need on create method to use sqlite sync but in other thread to update another table async.

public class DatabaseHelper
    {
        private static SQLiteConnection sqlConnection;
        private static SQLiteAsyncConnection sqlConnectionAsync;
        public static SQLiteConnection db()
        {
            if(sqlConnection == null)
                sqlConnection = new SQLiteConnection(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "student.db3"));
                               
            return sqlConnection;
        }
        public static SQLiteAsyncConnection dbAsync()
        {
            if (sqlConnectionAsync == null)
                sqlConnectionAsync = new SQLiteAsyncConnection(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "student.db3"));
           
            return sqlConnectionAsync;
        }
    }

OnCreate Method

datasource= DatabaseHelper.db().Table<Items>();
await DatabaseHelper.dbAsync().DeleteAll<Customers>();

Solution

  • This is safe, yes. As long as separate connections are used for concurrent access, then you can use synchronous or asynchronous APIs.

    There's another question you didn't ask: is it useful? The last time I checked, SQLite database drivers are synchronous-only, and the "asynchronous" APIs actually run synchronously. They'll work just fine; they just may not unblock the UI, and you may need to use Task.Run to throw the work on a background thread even for asynchronous APIs.