我正在尝试编写一个控制台应用程序,该应用程序接收来自我的网站的更改并在触发时执行某些操作。我让它连接并工作得很好,但是如果网站因任何原因和任何持续时间出现故障,客户端永远不会重新连接。这是我的客户代码:
public class MyBot
{
HubConnection connection;
public async Task RunAsync()
{
try
{
connection = new HubConnectionBuilder()
.WithUrl("https://localhost:7178/MyHub")
.WithAutomaticReconnect()
.Build();
connection.Closed += async (error) =>
{
Console.WriteLine("Connection Lost");
await Task.Delay(new Random().Next(0, 5) * 1000);
await connection.StartAsync();
await connection.InvokeAsync("JoinBots");
};
connection.On<string, string>("DoSomething", (arg1, arg2) =>
{
//Do Something
});
await connection.StartAsync();
await connection.InvokeAsync("JoinBots");
}
catch
{
Console.WriteLine("Failed to connect to Website");
}
}
}
在我的控制台中,永远不会写入“连接丢失”。事实上,没有一个能着火。我做错了什么?
因此,
connection.Closed
事件似乎仅在重试完成后才会触发。对此不是 100% 确定,但我认为它是如何工作的。
有一个
connection.Reconnected
方法会在连接丢失时触发。它只会触发一次,因此您可以在此处记录连接丢失的情况。
选项
WithAutomaticReconnect()
带有一个参数,在这里您可以设置自己的自定义重新连接。如果您想继续尝试,永不停止,或尝试 4 次后停止,或者以您认为合适的方式停止。
一旦我实现了上述一切,一切都工作正常。
编辑:
这是示例:
var connection = new HubConnectionBuilder()
.WithUrl($"someurl")
.WithAutomaticReconnect(new SignalRRetryPolicy())
.Build();
然后你可以像这样构建你的类:
public class SignalRRetryPolicy : IRetryPolicy
{
public TimeSpan? NextRetryDelay(RetryContext retryContext)
{
//replace this with whatever logic you want. Below is just example how to retry every 30 seconds and never stop. I would advise putting in place some sort of a stop after maybe few hours or such. But it depends on your scenario.
return TimeSpan.FromSeconds(30);
}
}