SignalR .Net 客户端异步重新连接

SignalR .Net client async reconnect

我的 WPF 应用程序 运行 在本地使用 SignalR .Net Client 通过异步代码连接到 SignalR hub。

我想解决 SignalR 集线器出现故障并且当 SignalR 集线器在例如 10 分钟后重新联机时 WPF 应用程序自动重新连接的情况。我想向 HubConnection 关闭事件注册一个异步操作。自动 SignalR 重新连接逻辑非常棒,但当超过超时时,它仍应重新连接到集线器。该示例使用 Polly 在连接关闭后重试直到成功。

以下代码的问题在于无法控制异步操作​​ (HubConnectionClosedEventHandler),并且在关闭 WPF 应用程序时它无法正确处理那些 运行 任务。还有一个奇怪的行为,即 Log4Net 在重试几次后停止记录。将异步操作注册到已关闭事件以尝试重新连接的最佳做法是什么?我做错了什么?

private async Task InitializeAsync()
{
   this.hubConnection.Closed += this.HubConnectionClosedEventHandler();
}

private Action HubConnectionClosedEventHandler()
{
    return () => this.HubConnectionClosed().Wait();
}

private async Task HubConnectionClosed()
{
    App.LogDebug("Connection closed event triggered.");
    await this.StartSignalRConnection();
}

private async Task StartSignalRConnection()
{
    App.LogDebug("Initialize policy.");
    var policy = Policy.Handle<Exception>().WaitAndRetryForeverAsync(retryAttempt => TimeSpan.FromSeconds(2));
    await policy.ExecuteAsync(this.StartSignalRConnectionAsync);
 }

private async Task StartSignalRConnectionAsync()
{
    App.LogDebug("Start connection.");
    await this.hubConnection.Start()
                .ContinueWith(
                    task =>
                        {
                            if (task.Exception != null || task.IsFaulted)
                            {
                                var exceptionMessage =
                                    $"There was an error opening the connection with connection '{CustomSettings.CallcenterHubConnection}'";
                                App.LogError(exceptionMessage,
                                    task.Exception);
                                throw new InvalidOperationException(exceptionMessage);
                            }

                            App.LogDebug(
                                $"Connected successfully with connection '{CustomSettings.CallcenterHubConnection}'");
                        });
}

public void Stop()
{
    try
    {
        this.hubConnection.Closed -= this.HubConnectionClosedEventHandler();
        if (this.hubConnection.State != ConnectionState.Disconnected) this.hubConnection.Stop();
    }
    catch (Exception ex)
    {
        App.LogError("Exception when stopping", ex);
    }
}

劫持关闭事件以重新连接似乎是错误的。最后,我们最终将断开连接超时更改为 5 分钟,并使用断开连接图标可视化 WPF 工具。如果服务器有一些严重的问题并且已修复,则用户必须手动重新启动 WPF 工具。