添加SQLite后XAML Hot Reload初始化失败,应用卡在.NET启动页
问题根源与修复方案
你的应用卡在启动屏的核心原因是构造函数中使用.Wait()同步等待异步操作,引发UI线程死锁。在.NET MAUI中,UI线程的同步上下文会等待异步任务完成,但异步任务中的await又需要回到UI线程继续执行,两者互相阻塞,导致启动流程卡死。
以下是具体的排查和修复步骤:
1. 修复异步操作阻塞问题
将数据库初始化和数据加载从构造函数移到OnAppearing方法中,用异步方式执行,避免同步阻塞:
public partial class MainPage : ContentPage { private SQLiteAsyncConnection _database; // 改用ObservableCollection,自动通知UI更新,无需手动重置ItemsSource private ObservableCollection<Notes> items; public MainPage() { items = new ObservableCollection<Notes>(); InitializeComponent(); NotesView.ItemsSource = items; HelpLabel.IsVisible = items.Count == 0; } protected override async void OnAppearing() { base.OnAppearing(); // 异步初始化数据库,避免阻塞UI线程 await CreateDatabaseAndTableAsync(); await LoadNotesFromDatabase(); } private async Task CreateDatabaseAndTableAsync() { // MAUI中需使用正确的应用数据目录,避免权限问题 string dbPath = Path.Combine(FileSystem.AppDataDirectory, "notes.db3"); _database = new SQLiteAsyncConnection(dbPath); await _database.CreateTableAsync<Notes>(); } private async Task LoadNotesFromDatabase() { var notes = await _database.Table<Notes>().ToListAsync(); items.Clear(); foreach (var note in notes) { items.Add(note); } HelpLabel.IsVisible = items.Count == 0; } }
2. 优化数据绑定逻辑
用ObservableCollection<Notes>替代List<Notes>,集合内容变化时会自动通知UI更新,无需手动执行NotesView.ItemsSource = null; NotesView.ItemsSource = items;这类重复操作。
3. 检查Notes实体类定义
确保实体类符合SQLite要求,必须包含主键(建议用自增主键):
public class Notes { [PrimaryKey, AutoIncrement] public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } }
如果主键缺失或标记错误,CreateTableAsync会抛出异常,结合之前的.Wait()会直接导致死锁。
4. 排查其他潜在问题
- 确认已正确安装
sqlite-net-pclNuGet包,版本需与.NET MAUI兼容; - 添加异常捕获,输出调试信息定位问题:
private async Task CreateDatabaseAndTableAsync() { try { string dbPath = Path.Combine(FileSystem.AppDataDirectory, "notes.db3"); _database = new SQLiteAsyncConnection(dbPath); await _database.CreateTableAsync<Notes>(); } catch (Exception ex) { Debug.WriteLine($"数据库初始化错误:{ex.Message}\n{ex.StackTrace}"); throw; } } - 检查设备/模拟器的文件权限,确保应用能读写应用数据目录。
内容的提问来源于stack exchange,提问作者Manos Stg
相关产品推荐
相关产品推荐

