我在使用 signalR hub 时遇到一些问题,我需要调用某种方法 每当我收到来自外部服务的请求时,都会从 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 的方法,则它似乎由于网络问题而无法连接然后调用 hub 方法,你会怎么做?
我并不是要求一个直接的解决方案,一个例子/文档链接仍然很棒,我确实在寻找一种方法来处理这个问题,但没有运气
抱歉,我没有正确查看文档, 这是我一直在寻找的答案:
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);
}
}}