@@ -149,12 +149,9 @@ private void Process()
149149 {
150150 try
151151 {
152- _heartRateMonitor ? . Start ( ) ;
153-
154152 while ( ! ( _cancellationTokenSource ? . Token . IsCancellationRequested ?? true ) )
155153 {
156- if ( _heartRateMonitor != null && _numberOfException == 0 && _heartRateMonitor . ElapsedMilliseconds > _heartRateMilliseconds )
157- Heartbeat ( ) ;
154+ Heartbeat ( ) ;
158155
159156 var message = ReceiveMessage ( ) ;
160157
@@ -240,7 +237,7 @@ private void ErrorHandler(ITransactionalMessage message, Exception exception)
240237 else
241238 message . NAck ( ) ;
242239 }
243- catch ( Exception ex )
240+ catch ( Exception ex )
244241 {
245242 _logger . Information ( ex , "Exception in Error Handler {QueueName} {@Message} {@Exception}" , _queueName , message , exception ) ;
246243
@@ -263,13 +260,26 @@ private bool CallErrorHandler(object message, Exception exception)
263260
264261 private void Heartbeat ( )
265262 {
263+ if ( _heartbeatHandler == null )
264+ return ;
265+
266+ if ( ! _heartRateMonitor . IsRunning )
267+ {
268+ _heartRateMonitor . Start ( ) ;
269+
270+ return ;
271+ }
272+
273+ if ( _numberOfException > 0 || _heartRateMonitor ? . ElapsedMilliseconds < _heartRateMilliseconds )
274+ return ;
275+
266276 _logger . Debug ( "Heartbeat Handler called {QueueName}" , _queueName ) ;
267277
268278 try
269279 {
270- _heartbeatHandler ? . Invoke ( ) ;
280+ _heartbeatHandler . Invoke ( ) ;
271281 }
272- catch ( Exception exception )
282+ catch ( Exception exception )
273283 {
274284 _logger . Warning ( exception , "Error in Heartbeat Handler {QueueName}" , _queueName ) ;
275285 }
@@ -306,21 +316,24 @@ private void CleanUpTasks()
306316 {
307317 if ( _numberOfException == 0 )
308318 {
309- _logger . Debug ( "Cleaning up dead tasks {QueueName}" , _queueName ) ;
310-
311319 try
312320 {
313- foreach ( var task in _workTasks . Where ( t => t . IsCompleted || t . IsFaulted ) )
321+ if ( _workTasks . Any ( ) )
314322 {
315- if ( task . IsFaulted )
316- CallErrorHandler ( task . AsyncState , task . Exception ) ;
323+ _logger . Debug ( "Cleaning up dead tasks {QueueName}" , _queueName ) ;
317324
318- task . Dispose ( ) ;
319- }
325+ foreach ( var task in _workTasks . Where ( t => t . IsCompleted || t . IsFaulted ) )
326+ {
327+ if ( task . IsFaulted )
328+ CallErrorHandler ( task . AsyncState , task . Exception ) ;
329+
330+ task . Dispose ( ) ;
331+ }
320332
321- _workTasks . RemoveAll ( t => t . IsCompleted || t . IsFaulted ) ;
333+ _workTasks . RemoveAll ( t => t . IsCompleted || t . IsFaulted ) ;
334+ }
322335 }
323- catch ( Exception exception )
336+ catch ( Exception exception )
324337 {
325338 _logger . Information ( exception , "Error in cleaning up dead tasks {QueueName}" , _queueName ) ;
326339 }
0 commit comments