22using System . Collections . Generic ;
33using System . Linq ;
44using System . Threading ;
5+ using System . Threading . Channels ;
56using System . Threading . Tasks ;
67using InEngine . Core . Exceptions ;
78using InEngine . Core . IO ;
@@ -29,17 +30,16 @@ public class RedisClient : IQueueClient
2930
3031 public string FailedQueueName => QueueBaseName + $ ":{ QueueName } :{ QueueNames . Failed } ";
3132
32- public static Lazy < ConnectionMultiplexer > lazyConnection = new Lazy < ConnectionMultiplexer > ( ( ) =>
33+ public static readonly Lazy < ConnectionMultiplexer > LazyConnection = new ( ( ) =>
3334 {
3435 var redisConfig = ConfigurationOptions . Parse ( $ "{ ClientSettings . Host } :{ ClientSettings . Port } ") ;
3536 redisConfig . Password = string . IsNullOrWhiteSpace ( ClientSettings . Password ) ? null : ClientSettings . Password ;
3637 redisConfig . AbortOnConnectFail = false ;
3738 return ConnectionMultiplexer . Connect ( redisConfig ) ;
3839 } ) ;
3940
40- public static ConnectionMultiplexer Connection => lazyConnection . Value ;
41+ public static ConnectionMultiplexer Connection => LazyConnection . Value ;
4142
42- public ConnectionMultiplexer _connectionMultiplexer ;
4343 private bool isDisposed ;
4444
4545 public IDatabase Redis => Connection . GetDatabase ( ClientSettings . Database ) ;
@@ -87,12 +87,11 @@ public async Task Consume(CancellationToken cancellationToken)
8787 try
8888 {
8989 InitChannel ( ) ;
90- Connection . GetSubscriber ( ) . Subscribe ( RedisChannel ,
91- delegate
92- {
93- Task . Factory . StartNew ( Consume , cancellationToken , TaskCreationOptions . LongRunning ,
94- TaskScheduler . Default ) ;
95- } ) ;
90+ var channelMessageQueue = await Connection . GetSubscriber ( ) . SubscribeAsync ( RedisChannel ) ;
91+ channelMessageQueue . OnMessage ( async _ =>
92+ {
93+ await Consume ( ) ;
94+ } ) ;
9695 }
9796 catch ( OperationCanceledException exception )
9897 {
@@ -108,8 +107,7 @@ public async Task<ICommandEnvelope> Consume()
108107 {
109108 var rawRedisMessageValue = Redis . ListRightPopLeftPush ( PendingQueueName , InProgressQueueName ) ;
110109 var serializedMessage = rawRedisMessageValue . ToString ( ) ;
111- if ( serializedMessage == null )
112- return null ;
110+
113111 var commandEnvelope = serializedMessage . DeserializeFromJson < CommandEnvelope > ( ) ;
114112 if ( commandEnvelope == null )
115113 throw new CommandFailedException ( "Could not deserialize the command." ) ;
@@ -189,11 +187,10 @@ public void Dispose()
189187
190188 private void Dispose ( bool disposing )
191189 {
192- if ( isDisposed )
190+ if ( isDisposed )
193191 return ;
194- if ( ! disposing )
192+ if ( ! disposing )
195193 return ;
196- _connectionMultiplexer ? . Dispose ( ) ;
197194 isDisposed = true ;
198195 }
199196}
0 commit comments