c# ASP.NET Core SignalR 客户端配置自动重连次数

自动重新连接

csharp 复制代码
HubConnection connection= new HubConnectionBuilder()
    .WithUrl(new Uri("http://127.0.0.1:5000/chathub"))
    .WithAutomaticReconnect()
    .Build();

在没有任何参数的情况下,WithAutomaticReconnect() 将客户端配置为在每次尝试重新连接之前分别等待 0、2、10 和 30 秒,在四次尝试失败后停止。

如果想要更好地控制自动重新连接尝试的时间安排和次数,则 WithAutomaticReconnect 需接受实现 IRetryPolicy 接口的对象,该对象具有一个名为 NextRetryDelay 的方法。

csharp 复制代码
public class RandomRetryPolicy : IRetryPolicy
{
    private readonly Random _random = new Random();

    public TimeSpan? NextRetryDelay(RetryContext retryContext)
    {
        // If we've been reconnecting for less than 60 seconds so far,
        // wait between 0 and 10 seconds before the next reconnect attempt.
        if (retryContext.ElapsedTime < TimeSpan.FromSeconds(60))
        {
            return TimeSpan.FromSeconds(_random.NextDouble() * 10);
        }
        else
        {
            // If we've been reconnecting for more than 60 seconds so far, stop reconnecting.
            return null;
        }
    }
}

参考连接:https://learn.microsoft.com/zh-cn/aspnet/core/signalr/dotnet-client?view=aspnetcore-9.0&tabs=visual-studio

相关推荐
hhh3u3u3u5 小时前
Visual C++ 6.0中文版安装包下载教程及win11安装教程
java·c语言·开发语言·c++·python·c#·vc-1
加号35 小时前
【C#】实现沃德普线光控制器通信控制(附完整源码)
开发语言·c#
lzhdim6 小时前
SharpCompress:跨平台的 C# 压缩与解压库
开发语言·c#
~plus~8 小时前
.NET 8 C# 委托与事件实战教程
网络·c#·.net·.net 8·委托与事件·c#进阶
beyond谚语9 小时前
接口&抽象类
c#·接口隔离原则·抽象类
新手小新9 小时前
C#学习笔记1-在VS CODE部署C#开发环境
笔记·学习·c#
csdn_aspnet10 小时前
在 .NET Core 8 中实现 CORS
.netcore·跨域·cors·.net8
rockey62712 小时前
AScript动态脚本多语言环境支持
sql·c#·.net·script·eval·function·动态脚本
ou.cs13 小时前
c# SemaphoreSlim保姆级教程
开发语言·网络·c#
龙侠九重天13 小时前
ML.NET 实战:快速构建分类模型
分类·数据挖掘·c#·.net