標籤:
上篇文章已經實現了在UWP中使用SQLite作為本機存放區,作為移動端的程式,及時響應使用者的操作是提高使用者體驗的重要途徑,因此UWP的很多api都是非同步。那麼如何使SQLite支援非同步呢?
參考SQLite.Net-PCL的github頁面:https://github.com/oysteinkrog/SQLite.Net-PCL
可以看到SQLite.Net-PCL是支援非同步,在建立資料庫連結的時候,可以建立同步的SQLiteConnection,也可以建立非同步SQliteAsyncConnection:
SQliteAsyncConnection The SQLiteAsyncConnection class now takes a Func in the constructor instead of a path. This is done because the async classes are now just meant to be wrappers around the normal sqlite connection. To use SQLiteAsyncConnection just create an instance of a SQLiteConnectionWithLock and pass in that through a func, e.g.: new SQLiteAsyncConnection(()=>_sqliteConnectionWithLock); Please be aware that the Task.Run pattern used in SQLiteAsyncConnection can be considered an anti-pattern (libraries should not provide async methods unless they are truly async). This class is maintained for backwards compatability and for use-cases where async-isolation is handy. |
在之前的版本中,建立SQLiteAsyncConnection和SQLiteConnection的寫法是類似的,都是傳入一個資料庫檔案地址即可,但新版本中非同步建構函式有點變化,需要傳入一個Func。
接下來我們看一下如何使用非同步方式來使用SQLite。
一、添加SQLite.Net.Async-PCL支援
還是在上個例子裡直接改吧,首先我們之前添加的SQLite.Net-PCL是不支援非同步,需要添加另一個nuget包:
裝了這個就可以使用非同步了。
二、建立非同步資料庫連結
public SQLiteAsyncConnection GetDbConnectionAsync(){var connectionFactory = new Func<SQLiteConnectionWithLock>(() => new SQLiteConnectionWithLock(new SQLitePlatformWinRT(), new SQLiteConnectionString(DbFilePath, storeDateTimeAsTicks: false)));var asyncConnection = new SQLiteAsyncConnection(connectionFactory);return asyncConnection;
把初始化方法改為:
public async Task InitAsync(){DbFilePath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, DbFileName);var db = GetDbConnectionAsync();await db.CreateTableAsync<UserItem>();}
注意要在StartupFunctions.cs檔案裡調用這個非同步,把原來那個Init方法注釋掉。
三、非同步訪問資料庫
其實之後就沒有太多可說的了,就是把原來的同步方法改成非同步就可以了,比如插入資料:
public async Task<int> InsertUserAsync(UserItem item){int result = 0;var conn = DbContext.Instance.GetDbConnectionAsync();result = await conn.InsertAsync(item);return result;}
擷取全部資料:
public async Task<List<UserItem>> GetAllUserAsync(){List<UserItem> result = new List<UserItem>();var conn = DbContext.Instance.GetDbConnectionAsync();result = await conn.Table<UserItem>().ToListAsync();return result;}
查詢的話可以這樣:
public async Task<List<UserItem>> GetUserListAsync(string key){List<UserItem> result = new List<UserItem>();var conn = DbContext.Instance.GetDbConnectionAsync();result = await conn.Table<UserItem>().Where(x => x.UserName.Contains(key)).ToListAsync();return result;}
其他幾個Update和Delete也有相應的非同步方法呼叫,就不寫了。
還有幾個方法是QueryAsync、ExecuteAsync、ExecuteScalarAsync等等,都可以直接執行sql語句,例如:
public async Task<int> GetUserCount(){var conn = DbContext.Instance.GetDbConnectionAsync();return await conn.ExecuteScalarAsync<int>("select count(*) from UserItem");}
建議使用非同步方式以獲得更好的效能。
Win10 UWP 開發系列:支援非同步SQLite