上篇文章已經實現了在UWP中使用SQLite作為本地存儲,作為移動端的程序,及時響應用戶的操作是提高用戶體驗的重要途徑,因此UWP的很多api都是異步的。那么如何使SQLite支持異步呢?
參考SQLite.Net-PCL的github頁面:https://github.com/oysteinkrog/SQLite.Net-PCL
可以看到SQLite.Net-PCL是支持異步的,在創建數據庫鏈接的時候,可以創建同步的SQLiteConnection,也可以創建異步的SQliteAsyncConnection:
SQliteAsyncConnectionThe 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"); }
建議使用異步的方式以獲得更好的性能。
