簡體   English   中英

SignalR,如何處理 Startasync 失敗

[英]SignalR , how to handle Startasync failing

我在使用 signalR 集線器時遇到了一些問題,每當我收到來自外部服務的請求時,我都需要從 signalR 集線器調用某個方法。 每當我收到這樣的“請求”時,我都會連接到 signalRhub,然后調用它的一種方法。

 string hostname = Environment.GetEnvironmentVariable("FRONTEND_HOSTNAME");
                    HubConnection connection;

                    connection = new HubConnectionBuilder()
                    .WithUrl($"{hostname}/xxx")
                    .Build();

                    await connection.StartAsync();
                    var resp = new
                    {
                        xx:'xx',
                    };
                    await connection.InvokeAsync("SendReport", resp);

                    connection.Closed += async (error) =>
                    {
                        await Task.Delay(new Random().Next(0, 5) * 1000);
                        await connection.StartAsync();
                    };

整個實現已經完成,雖然我似乎能夠連接和發送消息幾乎總是沒有問題,但是 StartAsync() 方法有時會失敗並拋出異常“名稱或服務未知”,以我看起來由於網絡問題而無法連接,如果您必須實現一種方法來重試 StartAsync 幾次然后調用集線器方法,您會怎么做?

我不是要一個直接的解決方案,一些東西的例子/文檔鏈接仍然很好,我確實在尋找一種方法來處理這個問題但沒有運氣

抱歉,我似乎沒有在文檔中正確查看,這是我正在尋找的答案:

public static async Task<bool> ConnectWithRetryAsync(HubConnection connection, CancellationToken token){
// Keep trying to until we can start or the token is canceled.
while (true)
{
    try
    {
        await connection.StartAsync(token);
        Debug.Assert(connection.State == HubConnectionState.Connected);
        return true;
    }
    catch when (token.IsCancellationRequested)
    {
        return false;
    }
    catch
    {
        // Failed to connect, trying again in 5000 ms.
        Debug.Assert(connection.State == HubConnectionState.Disconnected);
        await Task.Delay(5000);
    }
}}

https://docs.microsoft.com/en-us/aspnet/core/signalr/dotnet-client?view=aspnetcore-6.0&tabs=visual-studio

暫無
暫無

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

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