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

相关推荐
Avalon7129 分钟前
Unity3D响应式渲染UI框架UniVue
游戏·ui·unity·c#·游戏引擎
njsgcs25 分钟前
solidworks折弯自动标注5 非90度折弯
c#·solidworks
狼与自由1 小时前
clickhouse引擎
clickhouse·c#·linq
wangnaisheng1 小时前
【C#】死锁详解:发生原因、优化解决方案
c#
tiger从容淡定是人生2 小时前
AI替代软件战略(一):从 CCleaner 到 MCP 架构重构 —— TigerCleaner 的工程实践
人工智能·重构·架构·c#·mcp
宝桥南山21 小时前
GitHub Models - 尝试一下使用GitHub Models
microsoft·ai·微软·c#·github·.netcore
hixiong1231 天前
C# OpenvinoSharp部署INSID3
开发语言·人工智能·ai·c#·openvinosharp
星辰徐哥1 天前
Unity C#入门:变量的定义与访问权限(public/private)
unity·c#·lucene
leoufung1 天前
LeetCode 30:Substring with Concatenation of All Words 题解(含 C 语言 uthash 实现)
c语言·leetcode·c#
hacker7071 天前
Visual Studio安装教程(C#开发版)
ide·c#·visual studio