private async Task MessageReceivedAsync(QueueMessage <TMessage> message, CancellationToken cancellationToken) { using (var performanceLogger = new PerformanceLogger(performanceLoggingMethodName)) { try { if (Behaviour == AcknowledgeBehaviour.BeforeProcess) { _queueConsumer.AcknowledgeMessage(message.DeliveryTag); } await ProcessMessageAsync(message.Message, message.DeliveryTag, cancellationToken, message.RoutingKey); if (Behaviour == AcknowledgeBehaviour.AfterProcess) { _queueConsumer.AcknowledgeMessage(message.DeliveryTag); } if (Behaviour != AcknowledgeBehaviour.Never && Behaviour != AcknowledgeBehaviour.Deferred) { _logger.InfoFormat(Resources.MessageProcessedLogEntry, message.DeliveryTag); } } catch (AlreadyClosedException ex) { _logger.Warn($"The connection to Rabbit was closed while processing message with deliveryTag '{message.DeliveryTag}', error details - '{ex.Message}'."); } catch (FatalErrorException e) { if (Behaviour == AcknowledgeBehaviour.AfterProcess || Behaviour == AcknowledgeBehaviour.Async) { _queueConsumer.NegativelyAcknowledgeAndRequeue(message.DeliveryTag); } _logger.Fatal(Resources.FatalErrorLogEntry, e); } catch (Exception e) { _logger.ErrorFormat(Resources.ProcessingErrorLogEntry, message.DeliveryTag, e); if (Behaviour == AcknowledgeBehaviour.AfterProcess || Behaviour == AcknowledgeBehaviour.Async) { _queueConsumer.NegativelyAcknowledge(message.DeliveryTag); } } } }
private Func <Task> RunSequentialProcessor(ProcessingQueue <TMessage> processingQueue, CancellationToken cancellationToken) { return(async() => { QueueMessage <TMessage> dequeuedMessage; while (!cancellationToken.IsCancellationRequested && processingQueue.Queue.TryPeek(out dequeuedMessage)) { using (var performanceLogger = new PerformanceLogger(performanceLoggingMethodName)) { _logger.DebugFormat(Resources.MessageReceivedLogEntry, dequeuedMessage.DeliveryTag); try { await ProcessMessageAsync( dequeuedMessage.Message, dequeuedMessage.DeliveryTag, cancellationToken, dequeuedMessage.RoutingKey); if (Behaviour != AcknowledgeBehaviour.Async) { _queueConsumer.AcknowledgeMessage(dequeuedMessage.DeliveryTag); } _logger.InfoFormat(Resources.MessageProcessedLogEntry, dequeuedMessage.DeliveryTag); } catch (FatalErrorException e) { _logger.Fatal(Resources.FatalErrorLogEntry, e); _queueConsumer.NegativelyAcknowledgeAndRequeue(dequeuedMessage.DeliveryTag); throw; } catch (Exception e) { _logger.ErrorFormat(Resources.ProcessingErrorLogEntry, dequeuedMessage.DeliveryTag, e); _queueConsumer.NegativelyAcknowledge(dequeuedMessage.DeliveryTag); } } // we have finished processing - remove the message from the queue and wait for the next one. processingQueue.Queue.TryDequeue(out dequeuedMessage); await processingQueue.AutoResetEvent.WaitOneAsync(); } }); }