Jordan Osier
Jordan Osier

Reputation: 42

Can I use duplicate detection to cancel a scheduled Azure service bus message?

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.

If you turn on duplicate detection and both messages have the same MessageId, does sending the second message prior to the scheduled enqueueing time of the first effectively cancel the scheduled message? Also, is it safe to assume that the second message will be ignored if the scheduled message is successfully queued first?

Upvotes: 1

Views: 662

Answers (1)

Fei Han
Fei Han

Reputation: 27793

If you turn on duplicate detection and both messages have the same MessageId, does sending the second message prior to the scheduled enqueueing time of the first effectively cancel the scheduled message?

I do a test with the following sample code, and find that the second message will be ignored.

var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

for (int i = 0; i < 2; i++)
{
    if (i == 0)
    {
        client.SendAsync(new BrokeredMessage("testmes1") { MessageId = "test1", ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddSeconds(60) }).Wait();
    }
    else
    {
        client.SendAsync(new BrokeredMessage("testmes2") { MessageId = "test1" }).Wait();
    }

} 

receive messages from the queue:

client.OnMessage(message =>
{
    Console.WriteLine(String.Format("Message body: {0}", message.GetBody<String>()));
    Console.WriteLine(String.Format("Message id: {0}", message.MessageId));
});

output:

enter image description here

If you'd like to cancel a scheduled Message, you can try to call CancelScheduledMessageAsync() method before that scheduled Message becomes active.

client.CancelScheduledMessageAsync(sequenceNumber).Wait();

Upvotes: 4

Related Questions