Search code examples
c#azure-servicebus-queuesazure-servicebus-topics

What happens when you try to cancel a scheduled Azure service bus message that has already been enqueued?


I'm trying to come up with the best way to schedule a message for an Azure service bus queue or topic while leaving the option open for immediately sending a message instead of the scheduled message. I want to make sure I can protect myself against creating a duplicate message if I try to send the replacement message right at or after the scheduled time of the first message.

What will happen if I try to cancel a scheduled message with CancelScheduledMessageAsync (for both QueueClient and TopicClient classes) after the message has already been enqueued? Will it throw an exception?


Solution

  • According to your description, I found a blog (Canceling Scheduled Messages) talking about the similar issue.

    Before version 3.3.1, a scheduled message needs to be canceled prior to becoming visible, it was not possible. And any attempt to access its value would result in InvalidOperationException. Therefore, any messages scheduled in the future and no longer needed would be "stuck" on the broker until the later time.

    With Microsoft Azure Service Bus >= 3.3.1 QueueClient or TopicClient can be used to schedule a message and cancel it later.

    Also, I have tested it on my side via the following code:

    BrokeredMessage brokerMsg= new BrokeredMessage("Hello World!!!");
    long sequenceNumber = await queueClient.ScheduleMessageAsync(brokerMsg, DateTimeOffset.UtcNow.AddSeconds(30));
    
    await Task.Delay(TimeSpan.FromMinutes(1));
    // Cancel scheduled message
    await queueClient.CancelScheduledMessageAsync(sequenceNumber);
    

    I logged into azure portal and checked ACTIVE MESSAGE COUNT and SCHEDULED MESSAGE COUNT. I could cancel the scheduled message before it becomes active, but if I cancel the scheduled message via the sequenceNumber after the scheduled message becomes active, then I would retrieve the exception as follows:

    enter image description here