From b83b5be4edede6451d577f9a2c5303e08792b075 Mon Sep 17 00:00:00 2001 From: Marc Gravell Date: Wed, 13 May 2026 15:50:08 +0100 Subject: [PATCH] enable TCP keep-alives --- docs/ReleaseNotes.md | 2 +- src/StackExchange.Redis/SocketManager.cs | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/docs/ReleaseNotes.md b/docs/ReleaseNotes.md index 685825f94..b15b561d2 100644 --- a/docs/ReleaseNotes.md +++ b/docs/ReleaseNotes.md @@ -8,7 +8,7 @@ Current package versions: ## Unreleased -- (none) +- Enable TCP keep-alives ## 2.13.1 diff --git a/src/StackExchange.Redis/SocketManager.cs b/src/StackExchange.Redis/SocketManager.cs index 146e576ff..7c521c93e 100644 --- a/src/StackExchange.Redis/SocketManager.cs +++ b/src/StackExchange.Redis/SocketManager.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics; using System.IO.Pipelines; using System.Net; using System.Net.Sockets; @@ -223,7 +224,18 @@ internal static Socket CreateSocket(EndPoint endpoint) ? new Socket(SocketType.Stream, protocolType) : new Socket(addressFamily, SocketType.Stream, protocolType); SocketConnection.SetRecommendedClientOptions(socket); - // socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false); + if (protocolType is ProtocolType.Tcp) + { + try + { + // enable TCP keep-alive (best effort only) + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); + } + catch (Exception ex) + { + Debug.WriteLine(ex.Message); + } + } return socket; }