| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Collections.Concurrent; |
| | | 6 | | using System.Collections.Generic; |
| | | 7 | | using System.Text; |
| | | 8 | | using System.Threading; |
| | | 9 | | using System.Threading.Tasks; |
| | | 10 | | using CoreWCF.Runtime; |
| | | 11 | | |
| | | 12 | | namespace CoreWCF.Channels |
| | | 13 | | { |
| | | 14 | | internal class TransportConnectionManager |
| | | 15 | | { |
| | 0 | 16 | | private long _lastConnectionId = long.MinValue; |
| | 0 | 17 | | private readonly ConcurrentDictionary<long, ConnectionReference> _connectionReferences = new ConcurrentDictionar |
| | | 18 | | |
| | 0 | 19 | | public long GetNewConnectionId() => Interlocked.Increment(ref _lastConnectionId); |
| | | 20 | | |
| | | 21 | | public void AddConnection(long id, NamedPipeConnection connection) |
| | | 22 | | { |
| | 0 | 23 | | var connectionReference = new ConnectionReference(id, connection, this); |
| | | 24 | | |
| | 0 | 25 | | if (!_connectionReferences.TryAdd(id, connectionReference)) |
| | | 26 | | { |
| | 0 | 27 | | throw new ArgumentException("Unable to add specified id.", nameof(id)); |
| | | 28 | | } |
| | 0 | 29 | | } |
| | | 30 | | |
| | | 31 | | public void RemoveConnection(long id) |
| | | 32 | | { |
| | 0 | 33 | | if (!_connectionReferences.TryRemove(id, out _)) |
| | | 34 | | { |
| | 0 | 35 | | throw new ArgumentException("No value found for the specified id.", nameof(id)); |
| | | 36 | | } |
| | 0 | 37 | | } |
| | | 38 | | |
| | | 39 | | // This is only called by the ConnectionManager when the connection reference becomes |
| | | 40 | | // unrooted because the application never completed. |
| | | 41 | | public void StopTracking(long id) |
| | | 42 | | { |
| | 0 | 43 | | if (!_connectionReferences.TryRemove(id, out _)) |
| | | 44 | | { |
| | 0 | 45 | | throw new ArgumentException("No value found for the specified id.", nameof(id)); |
| | | 46 | | } |
| | 0 | 47 | | } |
| | | 48 | | |
| | | 49 | | public async Task<bool> CloseAllConnectionsAsync(CancellationToken token) |
| | | 50 | | { |
| | 0 | 51 | | var closeTasks = new List<Task>(); |
| | | 52 | | |
| | 0 | 53 | | foreach (var kvp in _connectionReferences) |
| | | 54 | | { |
| | 0 | 55 | | if (kvp.Value.TryGetConnection(out var connection)) |
| | | 56 | | { |
| | 0 | 57 | | connection.RequestClose(); |
| | 0 | 58 | | closeTasks.Add(connection.ExecutionTask); |
| | | 59 | | } |
| | | 60 | | } |
| | | 61 | | |
| | 0 | 62 | | var allClosedTask = Task.WhenAll(closeTasks.ToArray()); |
| | 0 | 63 | | return await Task.WhenAny(allClosedTask).CancellableAsyncWait(token) == allClosedTask; |
| | 0 | 64 | | } |
| | | 65 | | } |
| | | 66 | | } |