gpt4 book ai didi

c# - SQLite-Net-PCL死锁问题

转载 作者:行者123 更新时间:2023-12-03 03:47:33 27 4
gpt4 key购买 nike

我使用 SQLite-PCL 和 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() 是同步的。这只是为了保持与类中其他方法相同的格式。

最佳答案

对于此类问题,常见的模式是使用异步工厂方法创建受影响的类。

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虚拟方法中一样,您可以在其中订阅页面/ View 的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;
}

关于c# - SQLite-Net-PCL死锁问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44348698/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com