簡體   English   中英

SignalR .Net客戶端異步重新連接

[英]SignalR .Net client async reconnect

我的WPF應用程序使用SignalR .Net Client在本地運行,以使用異步代碼連接到SignalR集線器。

我想解決一下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工具。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM