|
4 | 4 | using System.Net.Security; |
5 | 5 | using System.Security.Authentication; |
6 | 6 | using System.Security.Cryptography.X509Certificates; |
| 7 | + using System.Threading; |
| 8 | + using System.Threading.Tasks; |
7 | 9 | using global::RabbitMQ.Client; |
8 | 10 |
|
9 | 11 | class ConnectionFactory |
10 | 12 | { |
11 | 13 | readonly string endpointName; |
12 | 14 | readonly global::RabbitMQ.Client.ConnectionFactory connectionFactory; |
13 | | - readonly object lockObject = new object(); |
| 15 | + readonly SemaphoreSlim semaphoreSlim = new(1, 1); |
14 | 16 |
|
15 | 17 | public ConnectionFactory(string endpointName, ConnectionConfiguration connectionConfiguration, |
16 | 18 | X509Certificate2Collection clientCertificateCollection, bool disableRemoteCertificateValidation, |
@@ -76,21 +78,26 @@ public ConnectionFactory(string endpointName, ConnectionConfiguration connection |
76 | 78 | } |
77 | 79 | } |
78 | 80 |
|
79 | | - public IConnection CreatePublishConnection() => CreateConnection($"{endpointName} Publish", false); |
| 81 | + public async Task<IConnection> CreatePublishConnection(CancellationToken cancellationToken) => await CreateConnection($"{endpointName} Publish", false, cancellationToken); |
80 | 82 |
|
81 | | - public IConnection CreateAdministrationConnection() => CreateConnection($"{endpointName} Administration", false); |
| 83 | + public Task<IConnection> CreateAdministrationConnection(CancellationToken cancellationToken) => CreateConnection($"{endpointName} Administration", false, cancellationToken); |
82 | 84 |
|
83 | | - public IConnection CreateConnection(string connectionName, bool automaticRecoveryEnabled = true) |
| 85 | + public async Task<IConnection> CreateConnection(string connectionName, bool automaticRecoveryEnabled = true, CancellationToken cancellationToken = default) |
84 | 86 | { |
85 | | - lock (lockObject) |
| 87 | + await semaphoreSlim.WaitAsync(cancellationToken).ConfigureAwait(false); |
| 88 | + try |
86 | 89 | { |
87 | 90 | connectionFactory.AutomaticRecoveryEnabled = automaticRecoveryEnabled; |
88 | 91 | connectionFactory.ClientProperties["connected"] = DateTime.UtcNow.ToString("G"); |
89 | 92 |
|
90 | | - var connection = connectionFactory.CreateConnection(connectionName); |
| 93 | + var connection = await connectionFactory.CreateConnectionAsync(connectionName, cancellationToken); |
91 | 94 |
|
92 | 95 | return connection; |
93 | 96 | } |
| 97 | + finally |
| 98 | + { |
| 99 | + _ = semaphoreSlim.Release(); |
| 100 | + } |
94 | 101 | } |
95 | 102 | } |
96 | 103 | } |
0 commit comments