Microsoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool
A concrete implementation of IDbConnectionPool used by Microsoft.Data.SqlClient
to efficiently manage a pool of reusable DbConnectionInternal objects backing ADO.NET SqlConnection instances.
Primary Responsibilities:
Connection Reuse and Pooling: Uses two stacks (_stackNew and _stackOld) to manage idle connections. Ensures efficient reuse and limits new connection creation.Transaction-Aware Pooling: Tracks connections enlisted in Transaction using TransactedConnectionPool and TransactedConnectionList, ensuring proper context reuse.Concurrency and Synchronization: Uses wait handles and semaphores via PoolWaitHandles to coordinate safe multi-threaded access.Connection Lifecycle Management: Manages creation (CreateObject), deactivation (DeactivateObject), destruction (DestroyObject), and reclamation (ReclaimEmancipatedObjects) of internal connections.Error Handling and Resilience: Implements retry and exponential backoff in TryGetConnection and handles transient errors using _errorWait.Minimum Pool Size Enforcement: Maintains the MinPoolSize by spawning background tasks to create new connections when needed.Load Balancing Support: Honors LoadBalanceTimeout to clean up idle connections and distribute load evenly.Telemetry and Tracing: Uses SqlClientEventSource for extensive diagnostic tracing of connection lifecycle events.Pending Request Queue: Queues unresolved connection requests in _pendingOpens and processes them using background threads.Identity and Authentication Context: Manages identity-based reuse via a dictionary of DbConnectionPoolAuthenticationContext keyed by user identity.Key Concepts in Design:
Stacks and queues for free and pending connectionsSynchronization via WaitHandle, Semaphore, and ManualResetEventSupport for transaction enlistment and affinityTimer-based cleanup to prune idle or expired connectionsBackground thread spawning for servicing deferred requests and replenishing the pool
public ConcurrentDictionary<DbConnectionPoolAuthenticationContextKey, DbConnectionPoolAuthenticationContext> AuthenticationContexts { get; }
Return the pooled authentication contexts.
public DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
Creates a new connection to replace an existing connection
public bool TryGetConnection(DbConnection owningObject, TaskCompletionSource<DbConnectionInternal> taskCompletionSource, DbConnectionOptions userOptions, out DbConnectionInternal connection)