上篇文章已经实现了在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 = ; 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"); }
建议使用异步的方式以获得更好的性能。