I have the following Azure Service Bus code:
private async Task startInternalAsync(CancellationToken cancellationToken) {
await using var client = new ServiceBusClient(_connectionString);
try {
var processor = client.CreateProcessor(_queueName, new ServiceBusProcessorOptions {
ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete,
PrefetchCount = 100
});
processor.ProcessMessageAsync += messageHandler;
processor.ProcessErrorAsync += errorHandler;
await processor.StartProcessingAsync(cancellationToken);
await cancellationToken.WhenCanceled();
_logger.LogDebug("Cancellation requested. Stopping the receiver...");
await processor.StopProcessingAsync();
_logger.LogDebug("Stopped receiving messages.");
}
catch (TaskCanceledException) {
_logger.LogDebug("Cancellation requested. Exiting.");
}
catch (Exception ex) {
_logger.LogError("Message processing exception. Exiting.", ex.Message);
}
}
private async Task messageHandler(ProcessMessageEventArgs args) {
string body = args.Message.Body.ToString();
_logger.LogDebug($"Received msg: {body}");
// complete the message. message is deleted from the queue.
await args.CompleteMessageAsync(args.Message);
}
private async Task errorHandler(ProcessErrorEventArgs args) {
await Task.Yield();
_logger.LogError(args.Exception.ToString());
}
Do I actually need to call await args.CompleteMessageAsync(args.Message)
in my messageHandler
, though? I'm in ReceiveAndDelete
mode so that should immediately delete the message from the ASB queue upon retrieval, but is CompleteMessageAsync()
still needed in order to remove it from the local queue? Or can I just remove that call?
You don't need to call CompleteMessageAsync
as the message will automatically be deleted once delivered.
In fact, I remember that calling this method actually throws an error when the message was fetched in ReceiveAndDelete
mode.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With