Search code examples
.netazureasp.net-coreazureservicebusazure-servicebus-queues

Azure Service Bus: How to Renew Lock?


How do I renew the lock on a Receiving Queue Message Handler? On the Event Handler, test Message does not have renew lock property.

Message testMessage;

enter image description here

https://learn.microsoft.com/en-us/dotnet/api/microsoft.servicebus.messaging.brokeredmessage.renewlock?view=azure-dotnet


Solution

  • The RenewLock api link you posted above is from the old deprecated WindowsAzure.ServiceBus nuget package where RenewLock method was part of BrokeredMessage. enter image description here

    The current package Microsoft.Azure.ServiceBus (which you are rightly using) has RenewLockAsync method as part of the Receiver https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.servicebus.core.messagereceiver.renewlockasync?view=azure-dotnet. You can call that method from your QueueClient instance like queueClient.RenewLockAsync(testMessage) or queueClient.RenewLockAsync(message.SystemProperties.LockToken). enter image description here

    But instead of the hard work of doing it by hand, you can leverage the auto-renew lock feature by setting MaxAutoRenewDuration property of MessageHandlerOptions. That would be in method RegisterOnMessageHandlerAndReceiveMessages in this example.

            static void RegisterOnMessageHandlerAndReceiveMessages()
            {
                // Configure the MessageHandler Options in terms of exception handling, number of concurrent messages to deliver etc.
                var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
                {
                    // Maximum number of Concurrent calls to the callback `ProcessMessagesAsync`, set to 1 for simplicity.
                    // Set it according to how many messages the application wants to process in parallel.
                    MaxConcurrentCalls = 1,
    
                    // Indicates whether MessagePump should automatically complete the messages after returning from User Callback.
                    // False below indicates the Complete will be handled by the User Callback as in `ProcessMessagesAsync` below.
                    AutoComplete = false,
    
                    // https://learn.microsoft.com/en-us/azure/service-bus-messaging/message-transfers-locks-settlement#peeklock
                    MaxAutoRenewDuration = <some timespan>
                };
    
                // Register the function that will process messages
                queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
            }