You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI应用Debug正常,独立运行时Edit按钮失效且退出崩溃求助

.NET MAUI Release模式下Edit按钮失效及退出崩溃修复方案

一、Edit按钮失效修复

ClientServiceHistoryPage.xaml中,Edit按钮同时设置了Clicked事件和Command属性,但代码中并未定义EditServiceCommand命令。Release模式下绑定系统的严格检查会导致点击事件被忽略,只需移除无效的Command绑定:

修改前:

<Button Text="Edit"  BackgroundColor="LightGray" HeightRequest="35" WidthRequest="50"  Clicked="EditButton_Clicked" Command="{Binding EditServiceCommand}" />

修改后:

<Button Text="Edit"  BackgroundColor="LightGray" HeightRequest="35" WidthRequest="50"  Clicked="EditButton_Clicked" />

二、退出崩溃修复(SQLite异步死锁问题)

ServiceDatabase构造函数中使用.Wait()阻塞异步操作,Release模式下极易引发线程死锁,导致应用退出崩溃。需将同步等待改为异步初始化,并调整页面加载逻辑:

1. 修改ServiceDatabase构造函数

public class ServiceDatabase
{
    readonly SQLiteAsyncConnection _database;

    private ServiceDatabase(string dbPath)
    {
        _database = new SQLiteAsyncConnection(dbPath);
    }

    public static async Task<ServiceDatabase> InitializeAsync(string dbPath)
    {
        var db = new ServiceDatabase(dbPath);
        await db._database.CreateTableAsync<Service>();
        return db;
    }

    // 其余原有方法保持不变
}

2. 调整服务历史加载逻辑

将LoadServiceHistory改为异步方法,避免在构造函数中阻塞UI线程:

public ClientServiceHistoryPage(Client selectedClient)
{
    InitializeComponent();
    SelectedClient = selectedClient;
    ServiceHistory = new ObservableCollection<Service>();
    BindingContext = this;

    // 异步加载,避免阻塞初始化流程
    _ = LoadServiceHistoryAsync();
}

private async Task LoadServiceHistoryAsync()
{
    var dbPath = Path.Combine(FileSystem.AppDataDirectory, "service.db");
    var serviceDatabase = await ServiceDatabase.InitializeAsync(dbPath);
    var servicesForClient = await serviceDatabase.GetServicesForClientAsync(SelectedClient.ID);

    ServiceHistory.Clear();
    foreach (var service in servicesForClient)
    {
        ServiceHistory.Add(service);
    }
}

三、额外优化建议

  • 实体类实现属性变更通知:为Client和Service类添加INotifyPropertyChanged实现(可使用CommunityToolkit.Mvvm的[ObservableObject]特性简化),避免Release模式下绑定失效。
  • 移异步逻辑至生命周期方法:将数据加载逻辑移至OnAppearing,避免构造函数中异步操作的潜在问题:
protected override async void OnAppearing()
{
    base.OnAppearing();
    await LoadServiceHistoryAsync();
}
  • 清理资源:页面销毁时关闭SQLite连接,避免资源泄漏:
protected override async void OnDisappearing()
{
    base.OnDisappearing();
    // 若持有ServiceDatabase实例,可在此关闭连接
    // await _serviceDatabase._database.CloseAsync();
}

内容的提问来源于stack exchange,提问作者Morpheus Mm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 20:57:03