1
我的WPF应用程序使用SignalR.Net客户端在本地运行,以使用异步代码连接到SignalR集线器。SignalR .Net客户端异步重新连接
我想解决SignalR集线器故障以及WPF应用在SignalR集线器在例如10分钟后重新联机时自动重新连接的情况。我想向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);
}
}