【问题标题】:SignalR Reconnecting Event Not Firing Properly in Xamarin FormsSignalR 重新连接事件未在 Xamarin Forms 中正确触发
【发布时间】:2022-11-30 22:25:05
【问题描述】:

我正在编写连接到 SignalR 服务器的 Xamarin Forms Android 应用程序。我的目标是在用户的服务器连接丢失时提醒用户,但是当 HubConnection.Reconnecting 事件被触发时,我的处理程序的内容(如下所示)不会运行。这是代码:

public static class SignalRService
    {
        private static HubConnection _connection { get; set; }

        public static void SetupSignalRService(string url, string hubEndpoint)
        {
            _connection = new HubConnectionBuilder()
                .WithUrl($"{url}/{hubEndpoint}")
                .WithAutomaticReconnect()
                .Build();

            _connection.Reconnecting += Connection_Reconnecting;

        }

        public static async Task Connect()
        {
            await _connection.StartAsync();
        }

        public static Task Connection_Reconnecting(Exception arg)
        {
            Application.Current.MainPage.DisplayAlert("Reconnecting", "Check your server status.", "ok");
            return Task.CompletedTask;
        }

    }

使用断点时,我可以看到线程进入了开始代码块{ 和第一行,但在我继续后跳出该方法。我在 C# 控制台应用程序项目上尝试了非常相似的代码,该项目立即运行(使用 Console.WriteLine 而不是 DisplayAlert)。关于我还能尝试什么的任何想法?

【问题讨论】:

  • 你试过在 MainThread 上运行 DisplayAlert 吗?
  • 是的,成功了,谢谢!

标签: c# xamarin.forms event-handling signalr signalr.client


【解决方案1】:

非常感谢 users/1338/jason 提供的答案:

你试过在 MainThread 上运行 DisplayAlert 吗?

使用 Xamarin.Essentials 的MainThreadclass,代码确实有效:

public static Task Connection_Reconnecting(Exception arg)
{
        MainThread.BeginInvokeOnMainThread(() => 
            Application.Current.MainPage.DisplayAlert("Reconnecting", "Check your server status.", "ok"));
        return Task.CompletedTask;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2014-04-03
    • 2021-05-28
    • 1970-01-01
    • 2020-02-07
    • 2022-01-26
    • 2015-03-26
    相关资源
    最近更新 更多