1
- using System . Collections . Generic ;
1
+ using System . Collections . Concurrent ;
2
+ using System . Collections . Generic ;
3
+ using System . Linq ;
2
4
using System . Runtime . CompilerServices ;
3
5
using System . Threading . Tasks ;
4
6
@@ -7,8 +9,8 @@ namespace RabbitMQ.Client.ConsumerDispatching
7
9
#nullable enable
8
10
internal abstract class ConsumerDispatcherBase
9
11
{
10
- private static readonly FallbackConsumer fallbackConsumer = new FallbackConsumer ( ) ;
11
- private readonly Dictionary < string , IBasicConsumer > _consumers = new Dictionary < string , IBasicConsumer > ( ) ;
12
+ private static readonly FallbackConsumer s_fallbackConsumer = new FallbackConsumer ( ) ;
13
+ private readonly IDictionary < string , IBasicConsumer > _consumers = new ConcurrentDictionary < string , IBasicConsumer > ( ) ;
12
14
13
15
public IBasicConsumer ? DefaultConsumer { get ; set ; }
14
16
@@ -18,26 +20,17 @@ protected ConsumerDispatcherBase()
18
20
19
21
protected void AddConsumer ( IBasicConsumer consumer , string tag )
20
22
{
21
- lock ( _consumers )
22
- {
23
- _consumers [ tag ] = consumer ;
24
- }
23
+ _consumers [ tag ] = consumer ;
25
24
}
26
25
27
26
protected IBasicConsumer GetConsumerOrDefault ( string tag )
28
27
{
29
- lock ( _consumers )
30
- {
31
- return _consumers . TryGetValue ( tag , out IBasicConsumer ? consumer ) ? consumer : GetDefaultOrFallbackConsumer ( ) ;
32
- }
28
+ return _consumers . TryGetValue ( tag , out IBasicConsumer ? consumer ) ? consumer : GetDefaultOrFallbackConsumer ( ) ;
33
29
}
34
30
35
31
public IBasicConsumer GetAndRemoveConsumer ( string tag )
36
32
{
37
- lock ( _consumers )
38
- {
39
- return _consumers . Remove ( tag , out IBasicConsumer ? consumer ) ? consumer : GetDefaultOrFallbackConsumer ( ) ;
40
- }
33
+ return _consumers . Remove ( tag , out IBasicConsumer ? consumer ) ? consumer : GetDefaultOrFallbackConsumer ( ) ;
41
34
}
42
35
43
36
public void Shutdown ( ShutdownEventArgs reason )
@@ -54,14 +47,11 @@ public Task ShutdownAsync(ShutdownEventArgs reason)
54
47
55
48
private void DoShutdownConsumers ( ShutdownEventArgs reason )
56
49
{
57
- lock ( _consumers )
50
+ foreach ( KeyValuePair < string , IBasicConsumer > pair in _consumers . ToArray ( ) )
58
51
{
59
- foreach ( KeyValuePair < string , IBasicConsumer > pair in _consumers )
60
- {
61
- ShutdownConsumer ( pair . Value , reason ) ;
62
- }
63
- _consumers . Clear ( ) ;
52
+ ShutdownConsumer ( pair . Value , reason ) ;
64
53
}
54
+ _consumers . Clear ( ) ;
65
55
}
66
56
67
57
protected abstract void ShutdownConsumer ( IBasicConsumer consumer , ShutdownEventArgs reason ) ;
@@ -74,7 +64,7 @@ private void DoShutdownConsumers(ShutdownEventArgs reason)
74
64
[ MethodImpl ( MethodImplOptions . NoInlining ) ]
75
65
private IBasicConsumer GetDefaultOrFallbackConsumer ( )
76
66
{
77
- return DefaultConsumer ?? fallbackConsumer ;
67
+ return DefaultConsumer ?? s_fallbackConsumer ;
78
68
}
79
69
}
80
70
}
0 commit comments