[英]SQLite-Net-PCL Deadlock issue
我正在將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()
並調用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
虛擬方法中一樣,您可以在其中訂閱頁面/視圖的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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.