Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to call CompleteMessageAsync when I'm in ReceiveAndDelete mode?

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?

like image 292
Jez Avatar asked Aug 31 '25 20:08

Jez


1 Answers

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.

like image 98
Gaurav Mantri Avatar answered Sep 03 '25 09:09

Gaurav Mantri