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

相关推荐
BXS_null1 小时前
windows、linux/ubuntu 系统运用.net core使用Selenium WebDriver实现自动化测试
linux·ubuntu·.netcore
2501_930707782 小时前
使用C#代码在 Word 文档中查找并替换文本
开发语言·c#·word
一个帅气昵称啊4 小时前
在.NET中使用RAG检索增强AI基于Qdrant的矢量化数据库
ai·性能优化·c#·.net·rag·qdrant
还是大剑师兰特6 小时前
C#面试题及详细答案120道(86-95)-- 进阶特性
c#·大剑师
我是唐青枫8 小时前
C#.NET ControllerBase 深入解析:Web API 控制器的核心基石
c#·.net
O败者食尘D9 小时前
【C#】使用Enigma将Winform或WPF打包成一个exe
c#
The Sheep 202312 小时前
C# 吃一堑,长一智
c#
q***829118 小时前
如何使用C#与SQL Server数据库进行交互
数据库·c#·交互
hixiong12321 小时前
C# OpenCVSharp实现Hand Pose Estimation Mediapipe
开发语言·opencv·ai·c#·手势识别