diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs
index de92797218..ce007e86f3 100644
--- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs
+++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs
@@ -1101,7 +1101,11 @@ public override uint CheckConnection()
// Since _socket.Connected alone doesn't guarantee if the connection is still active, we use it in
// combination with _socket.Poll method and _socket.Available == 0 check. When both of them
// return true we can safely determine that the connection is no longer active.
- if (!_socket.Connected || (_socket.Poll(100, SelectMode.SelectRead) && _socket.Available == 0))
+ //
+ // The poll does not wait: a closed connection is already readable, so waiting adds nothing.
+ // Any positive timeout is rounded up to the system timer tick on Windows (15.6 ms by default),
+ // which this check would cost on every connection taken from the pool.
+ if (!_socket.Connected || (_socket.Poll(0, SelectMode.SelectRead) && _socket.Available == 0))
{
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Socket not usable.", args0: _connectionId);
return TdsEnums.SNI_ERROR;
diff --git a/src/Microsoft.Data.SqlClient/tests/PerformanceTests/BenchmarkRunners/ConnectionPoolIdleCheckoutRunner.cs b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/BenchmarkRunners/ConnectionPoolIdleCheckoutRunner.cs
new file mode 100644
index 0000000000..637cc8d061
--- /dev/null
+++ b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/BenchmarkRunners/ConnectionPoolIdleCheckoutRunner.cs
@@ -0,0 +1,91 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using BenchmarkDotNet.Attributes;
+
+namespace Microsoft.Data.SqlClient.PerformanceTests
+{
+ ///
+ /// Measures one checkout of a connection that has sat idle in the pool long enough to be
+ /// probed for liveness before it is handed out.
+ ///
+ /// The pool skips the liveness probe for a connection that did I/O or passed a probe within
+ /// the last 5 ms (TdsParserStateObject.CheckConnectionWindow). In the rapid open/close
+ /// loop of at most one checkout in every 5 ms is
+ /// probed, and its cost is averaged over the rest. Here every iteration waits past that window
+ /// outside the measurement, then times a single open, so every measured checkout pays for the
+ /// probe. Under managed SNI the probe is
+ /// SniTcpHandle.CheckConnection, whose socket poll must not wait: Windows rounds any
+ /// positive poll timeout up to the timer tick, about 15 ms by default.
+ ///
+ /// The pool holds a single connection, so every iteration probes the same idle socket. Set
+ /// UseManagedSniOnWindows to measure the managed probe on Windows; on other operating
+ /// systems the managed implementation is the only one.
+ ///
+ /// Related issue: #5070
+ ///
+ public class ConnectionPoolIdleCheckoutRunner : BaseRunner
+ {
+ ///
+ /// How long the connection sits idle before each measured checkout: twice the 5 ms window,
+ /// so clock granularity cannot leave it inside the window.
+ ///
+ private static readonly TimeSpan s_idleTime = TimeSpan.FromMilliseconds(10);
+
+ private string _connectionString;
+
+ [GlobalSetup]
+ public void Setup()
+ {
+ var builder = new SqlConnectionStringBuilder(s_config.ConnectionString)
+ {
+ Pooling = true,
+ // One connection, kept open, so each checkout probes the same idle socket rather
+ // than opening a new physical connection.
+ MinPoolSize = 1,
+ MaxPoolSize = 1
+ };
+ _connectionString = builder.ConnectionString;
+
+ // Opened and released before measurement, so no measured open is a physical connect.
+ using var conn = new SqlConnection(_connectionString);
+ conn.Open();
+ }
+
+ ///
+ /// Leaves the pooled connection idle past the liveness window, outside the measurement.
+ ///
+ [IterationSetup]
+ public void IterationSetup()
+ {
+ Thread.Sleep(s_idleTime);
+ }
+
+ [GlobalCleanup]
+ public void Cleanup()
+ {
+ using var conn = new SqlConnection(_connectionString);
+ SqlConnection.ClearPool(conn);
+ }
+
+ [Benchmark]
+ public void OpenIdlePooledConnection()
+ {
+ using var conn = new SqlConnection(_connectionString);
+ conn.Open();
+ // Dispose returns the connection to the pool.
+ }
+
+ [Benchmark]
+ public async Task OpenIdlePooledConnectionAsync()
+ {
+ await using var conn = new SqlConnection(_connectionString);
+ await conn.OpenAsync();
+ // Dispose returns the connection to the pool.
+ }
+ }
+}
diff --git a/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Config/Config.cs b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Config/Config.cs
index 6bf99f9f0f..1a2f41f967 100644
--- a/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Config/Config.cs
+++ b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Config/Config.cs
@@ -74,6 +74,7 @@ public class Benchmarks
public RunnerJob ConnectionPoolStressRunnerConfig;
public RunnerJob ConnectionPoolContentionRunnerConfig;
public RunnerJob ConnectionPoolChurnRunnerConfig;
+ public RunnerJob ConnectionPoolIdleCheckoutRunnerConfig;
public RunnerJob ConnectionPoolRampRunnerConfig;
public RunnerJob ConnectionPoolThreadPoolPressureRunnerConfig;
}
diff --git a/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Program.cs b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Program.cs
index 53533374a7..3ab019fc85 100644
--- a/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Program.cs
+++ b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/Program.cs
@@ -60,6 +60,7 @@ public BenchmarkUnit(string name, Func selector, Type run
new BenchmarkUnit("ConnectionPoolStress", b => b.ConnectionPoolStressRunnerConfig, typeof(ConnectionPoolStressRunner)),
new BenchmarkUnit("ConnectionPoolContention", b => b.ConnectionPoolContentionRunnerConfig, typeof(ConnectionPoolContentionRunner)),
new BenchmarkUnit("ConnectionPoolChurn", b => b.ConnectionPoolChurnRunnerConfig, typeof(ConnectionPoolChurnRunner)),
+ new BenchmarkUnit("ConnectionPoolIdleCheckout", b => b.ConnectionPoolIdleCheckoutRunnerConfig, typeof(ConnectionPoolIdleCheckoutRunner)),
new BenchmarkUnit("ConnectionPoolRamp", b => b.ConnectionPoolRampRunnerConfig, typeof(ConnectionPoolRampRunner)),
new BenchmarkUnit("ConnectionPoolThreadPoolPressure", b => b.ConnectionPoolThreadPoolPressureRunnerConfig, typeof(ConnectionPoolThreadPoolPressureRunner)),
};
diff --git a/src/Microsoft.Data.SqlClient/tests/PerformanceTests/runnerconfig.default.jsonc b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/runnerconfig.default.jsonc
index d7bb3cf5a0..8ddb244a8a 100644
--- a/src/Microsoft.Data.SqlClient/tests/PerformanceTests/runnerconfig.default.jsonc
+++ b/src/Microsoft.Data.SqlClient/tests/PerformanceTests/runnerconfig.default.jsonc
@@ -181,6 +181,16 @@
"WarmupCount": 1,
"RowCount": 0
},
+ // Each iteration times a single checkout, so it needs more iterations than the others
+ // for a stable median.
+ "ConnectionPoolIdleCheckoutRunnerConfig": {
+ "Enabled": true,
+ "LaunchCount": 1,
+ "IterationCount": 50,
+ "InvocationCount": 1,
+ "WarmupCount": 1,
+ "RowCount": 0
+ },
"ConnectionPoolRampRunnerConfig": {
"Enabled": true,
"LaunchCount": 1,
diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandleTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandleTests.cs
index c18041e9dd..4832352c75 100644
--- a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandleTests.cs
+++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandleTests.cs
@@ -5,6 +5,7 @@
#if NET
using System;
+using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
@@ -85,6 +86,74 @@ public async Task EnableSsl_PeerNeverAnswersHandshake_ReturnsTimeoutErrorWhenTok
handle.Dispose();
}
}
+
+ ///
+ /// The liveness check reports a connection the peer has closed, so the pool discards it
+ /// instead of handing it out. The peer's close reaches the client asynchronously, so the
+ /// check is repeated until it fails or a deadline passes.
+ ///
+ [Fact]
+ public void CheckConnection_PeerClosed_ReturnsError()
+ {
+ // Arrange
+ using LocalConnection connection = new();
+ connection.Peer.Close();
+
+ // Act
+ uint result = TdsEnums.SNI_SUCCESS;
+ Stopwatch deadline = Stopwatch.StartNew();
+ while (result == TdsEnums.SNI_SUCCESS && deadline.Elapsed < TimeSpan.FromSeconds(5))
+ {
+ result = connection.Handle.CheckConnection();
+ if (result == TdsEnums.SNI_SUCCESS)
+ {
+ Thread.Sleep(10);
+ }
+ }
+
+ // Assert
+ Assert.Equal(TdsEnums.SNI_ERROR, result);
+ }
+
+ ///
+ /// Opens a managed TCP handle to a local listener and owns both ends.
+ ///
+ private sealed class LocalConnection : IDisposable
+ {
+ public SniTcpHandle Handle { get; }
+
+ public Socket Peer { get; }
+
+ public LocalConnection()
+ {
+ using TcpListener listener = new(IPAddress.Loopback, 0);
+ listener.Start();
+ SQLDNSInfo? pendingDnsInfo = null;
+ Handle = new SniTcpHandle(
+ IPAddress.Loopback.ToString(),
+ ((IPEndPoint)listener.LocalEndpoint).Port,
+ TimeoutTimer.StartNew(TimeSpan.FromSeconds(5)),
+ parallel: false,
+ SqlConnectionIPAddressPreference.IPv4First,
+ cachedFQDN: nameof(SniTcpHandleTests),
+ ref pendingDnsInfo,
+ tlsFirst: false,
+ hostNameInCertificate: null,
+ serverCertificateFilename: null);
+ using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(5));
+ Peer = listener.AcceptSocketAsync(timeout.Token).AsTask().GetAwaiter().GetResult();
+ Assert.Equal(TdsEnums.SNI_SUCCESS, Handle.Status);
+ }
+
+ ///
+ /// Closes the client handle and the accepted socket.
+ ///
+ public void Dispose()
+ {
+ Handle.Dispose();
+ Peer.Dispose();
+ }
+ }
}
}