我使用SQLite和Xamarin.Android进行数据存储。我正在异步地使用它,并因此遇到了死锁问题。
实现包含在一个DataHandler类中:
构造器
public DataHandler(string path)
{
_db = new SQLiteAsyncConnection(path);
Initialize().Wait();
}初始化函数
private async Task Initialize()
{
using (await Lock())
{
await _db.CreateTableAsync<Person>();
await _db.CreateTableAsync<Animal>();
}
}最后,Lock()函数是这个问题的答案的实现:https://stackoverflow.com/a/44127898/3808312
在构造对象时,在第一次调用Initialize().Wait()时会调用CreateTableAsync()和死锁,不幸的是,如果不对其进行反汇编,我就无法真正调试到库中。我是不是用错了异步模式什么的?是的,我知道Wait()是同步的。这只是为了保持与类中其他方法相同的格式。
发布于 2017-06-03 21:58:24
对于这样的问题,一个常见的模式是使用异步工厂方法创建受影响的类。
public class DataHandler {
//...other code
private DataHandler() {
}
private async Task InitializeAsync(string path) {
_db = new SQLiteAsyncConnection(path);
using (await Lock()) {
await _db.CreateTableAsync<Person>();
await _db.CreateTableAsync<Animal>();
}
}
public static async Task<DataHandler> CreateDataHandler(string path) {
var handler = new DataHandler();
await handler.InitializeAsync(path);
return handler;
}
//...other code
}然后以允许异步调用的方式使用它。
var handler = await DataHandler.CreateDataHandler("<path here>");就像在OnAppearing虚拟方法中,可以订阅页面/视图的Appearing事件
protected override void OnAppearing() {
this.Appearing += Page_Appearing;
}并在实际的偶数处理程序上调用异步代码。
private async void Page_Appearing(object sender, EventArgs e) {
//...call async code here
var handler = await DataHandler.CreateDataHandler("<path here>");
//..do what you need to do with the handler.
//unsubscribing from the event
this.Appearing -= Page_Appearing;
}https://stackoverflow.com/questions/44348698
复制相似问题