From 1592f690d4339ec54e9d03f3d31bf3089db99a75 Mon Sep 17 00:00:00 2001 From: Denys Sidenko Date: Fri, 1 Sep 2023 10:54:25 +0200 Subject: [PATCH] Add timeout before reconnecting when the listened stream is lost (#127) Add timeout before reconnecting if the connection is lost with a transient error. Co-authored-by: Denis Sidenko --- src/Websocket.Client/IWebsocketClient.cs | 7 +++++++ src/Websocket.Client/WebsocketClient.cs | 16 +++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/Websocket.Client/IWebsocketClient.cs b/src/Websocket.Client/IWebsocketClient.cs index 36f5ec1..7b59b53 100644 --- a/src/Websocket.Client/IWebsocketClient.cs +++ b/src/Websocket.Client/IWebsocketClient.cs @@ -43,6 +43,13 @@ public interface IWebsocketClient : IDisposable /// Default: 1 minute. /// TimeSpan? ErrorReconnectTimeout { get; set; } + + /// + /// Time range in ms, how long to wait before reconnecting if connection is lost with a transient error. + /// Set null to disable this feature. + /// Default: 0 ms (immediately) + /// + TimeSpan? LostReconnectTimeout { get; set; } /// /// Get or set the name of the current websocket client instance. diff --git a/src/Websocket.Client/WebsocketClient.cs b/src/Websocket.Client/WebsocketClient.cs index 1318777..8a6707f 100644 --- a/src/Websocket.Client/WebsocketClient.cs +++ b/src/Websocket.Client/WebsocketClient.cs @@ -113,6 +113,13 @@ public Uri Url /// public TimeSpan? ErrorReconnectTimeout { get; set; } = TimeSpan.FromMinutes(1); + /// + /// Time range in ms, how long to wait before reconnecting if connection is lost with a transient error. + /// Set null to disable this feature. + /// Default: 0 ms (immediately) + /// + public TimeSpan? LostReconnectTimeout { get; set; } + /// /// Enable or disable reconnection functionality (enabled by default) /// @@ -560,12 +567,19 @@ await StopInternal(client, WebSocketCloseStatus.NormalClosure, "Closing", causedException = e; } - if (ShouldIgnoreReconnection(client) || !IsStarted) { // reconnection already in progress or client stopped/disposed, do nothing return; } + + if (LostReconnectTimeout.HasValue) + { + var timeout = LostReconnectTimeout.Value; + Logger.Warn(L("Listening websocket stream is lost. " + + $"Waiting {timeout.TotalSeconds} sec before next reconnection try.")); + await Task.Delay(timeout, token).ConfigureAwait(false); + } // listening thread is lost, we have to reconnect _ = ReconnectSynchronized(ReconnectionType.Lost, false, causedException);