Reputation: 75
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
Upvotes: 1
Views: 2656
Reputation: 75
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, token);
}
}}
Upvotes: 5