public void Dispose() { runCleanUpTask = false; try { @lock.Wait(); foreach (var queue in cache.Select(x => x.Value).ToList()) { while (!queue.IsEmpty) { TcpServerConnection connection; if (queue.TryDequeue(out connection)) { disposalBag.Add(connection); } } } cache.Clear(); } finally { @lock.Release(); } while (!disposalBag.IsEmpty) { TcpServerConnection connection = null; if (disposalBag.TryTake(out connection)) { connection?.Dispose(); } } }
/// <summary> /// Release connection back to cache. /// </summary> /// <param name="connection">The Tcp server connection to return.</param> /// <param name="close">Should we just close the connection instead of reusing?</param> internal void Release(TcpServerConnection connection, bool close = false) { if (close || connection.IsWinAuthenticated) { disposalBag.Add(connection); return; } connection.LastAccess = DateTime.Now; @lock.Wait(); while (true) { if (cache.TryGetValue(connection.CacheKey, out var existingConnections)) { existingConnections.Enqueue(connection); break; } if (cache.TryAdd(connection.CacheKey, new ConcurrentQueue <TcpServerConnection>(new[] { connection }))) { break; } ; } @lock.Release(); }
/// <summary> /// Release connection back to cache. /// </summary> /// <param name="connection">The Tcp server connection to return.</param> /// <param name="close">Should we just close the connection instead of reusing?</param> internal async Task Release(TcpServerConnection connection, bool close = false) { if (connection == null) { return; } if (close || connection.IsWinAuthenticated || !server.EnableConnectionPool) { disposalBag.Add(connection); return; } connection.LastAccess = DateTime.Now; try { await @lock.WaitAsync(); while (true) { ConcurrentQueue <TcpServerConnection> existingConnections; if (cache.TryGetValue(connection.CacheKey, out existingConnections)) { while (existingConnections.Count >= server.MaxCachedConnections) { TcpServerConnection staleConnection; if (existingConnections.TryDequeue(out staleConnection)) { disposalBag.Add(staleConnection); } } existingConnections.Enqueue(connection); break; } if (cache.TryAdd(connection.CacheKey, new ConcurrentQueue <TcpServerConnection>(new[] { connection }))) { break; } } } finally { @lock.Release(); } }
internal async Task Release(Task <TcpServerConnection> connectionCreateTask, bool closeServerConnection) { if (connectionCreateTask != null) { TcpServerConnection connection = null; try { connection = await connectionCreateTask; } catch { } finally { await Release(connection, closeServerConnection); } } }