简体   繁体   中英

SignalR , how to handle Startasync failing

I'm encountering some problems with a signalR hub , i need to invoke a certain method from a signalR hub whenever i receive a request from an external service . Whenever i do receive such "request" i connect to the signalRhub and then invoke one of its methods.

 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();
                    };

The whole implementation has already been done , although it seems that i'm able to connect & send messages ALMOST always without problems, however from time to time the StartAsync() method fails and throws an exception "Name or service not known" , to me it looks like it's unable to connect due to network issues , if you had to implement a way to retry the StartAsync a few times to then invoke the hub method, how would you do it?

I'm not asking for a straight solution , an example of something / links to documentation would still be great, i did search for a way to handle this but with no luck

Sorry it appears i didn't look properly within the documentation , here's the answer i was looking for:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM