Win10 UWP 开发系列:支持异步的SQLite
上篇文章已经实现了在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");
}
建议使用异步的方式以获得更好的性能。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
2012-11-20 华容道Win8版隐私声明