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



我的 WPF 应用正在使用 SignalR .Net Client 在本地运行,以使用异步代码连接到 SignalR 中心。

我想解决以下情况:当 SignalR 中心在 10 分钟后重新联机时,SignalR 中心关闭并且 WPF 应用会自动重新连接。我想向中心连接关闭事件注册一个异步操作。自动 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 工具。

最新更新