我有这个代码从SQLite数据库中检索单个对象,但是当我选择使用此代码的列表框项时,应用程序会冻结几秒钟。我想我必须将此代码修改为异步操作:
public FFSystems ReadFFSystem(int FFSystemID)
{
using (SQLiteConnection conn = new SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
var existingFFSystem = conn.Query<FFSystems>("select * from FFSystems where ID =" + FFSystemID).FirstOrDefault();
return existingFFSystem;
}
}
如何修改此代码?
答案 0 :(得分:1)
为您的项目安装此nuget包:SQLite.Net.Async-PCL
。
然后你可以像这样重构你的代码:
using SQLite.Net.Async;
private SQLiteConnectionWithLock GetAsyncConnection()
{
var localFolder = ApplicationData.Current.LocalFolder.Path;
var path = Path.Combine(localFolder, FileName);
var connString = new SQLiteConnectionString(path, true);
var conn = new SQLiteConnectionWithLock(new SQLitePlatformWinRT(), connString);
return conn;
}
public async Task<FFSystems> ReadFFSystemAsync(int FFSystemID)
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection(() => GetAsyncConnection());
return await conn.Table<FFSystems>().Where(s => s.ID ==FFSystemID).FirstOrDefaultAsync();
}
然后你可以得到这样的数据:
var obj = await ReadFFSystemAsync(5);