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

MAUI集成ASP.NET Core SignalR添加服务端调用方法时崩溃求助

解决方案
  • 修正UI线程调用问题
    SignalR的客户端方法回调运行在后台线程,而MAUI中所有UI操作(如DisplayAlert)必须在主线程执行。你的代码直接在后台线程调用UI操作,会触发线程异常导致崩溃。

    修改Getmsg方法,通过MainThread.InvokeOnMainThreadAsync将UI操作切换到主线程:

    private async void Getmsg(string s)
    {
        await MainThread.InvokeOnMainThreadAsync(() => 
        {
            DisplayAlert("提示", s, "确定");
        });
    }
    
  • 优化回调方法的异步处理
    建议将Getmsg改为async Task类型,同时在注册SignalR回调时使用async lambda,避免潜在的异步回调问题:

    // 注册回调时使用async lambda
    _connection.On<string>("broadcastMessage", async (s2) => await Getmsg(s2));
    
    // 修正后的Getmsg方法
    private async Task Getmsg(string s)
    {
        await MainThread.InvokeOnMainThreadAsync(() => 
        {
            DisplayAlert("提示", s, "确定");
        });
    }
    
  • 添加全局异常捕获辅助排查
    在App.xaml.cs中添加全局异常处理,捕获未处理的异常,方便后续排查其他潜在问题:

    protected override void OnStart()
    {
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
    }
    
    private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
    {
        MainThread.BeginInvokeOnMainThread(() => 
        {
            DisplayAlert("未捕获任务异常", e.Exception.ToString(), "确定");
        });
        e.SetObserved();
    }
    
    private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        MainThread.BeginInvokeOnMainThread(() => 
        {
            DisplayAlert("未捕获异常", (e.ExceptionObject as Exception)?.ToString() ?? "未知异常", "确定");
        });
    }
    

内容的提问来源于stack exchange,提问作者RUSHI HARDWARE

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 21:02:05