Azure.Messaging.ServiceBus: should I remove ProcessMessageAsync handler from ServiceBusProcessor on disposing?

Viewed 688

I am using Azure.Messaging.ServiceBus library.

I create ServiceBusClient and ServiceBusProcessor to start receiving queue messages like this:

var serviceBusClient = new ServiceBusClient(connectionString);
ServiceBusProcessor processor = serviceBusClient.CreateProcessor(queue);
processor.ProcessMessageAsync += HandleEvent;
processor.StartProcessingAsync();

On application shutdown I dispose ServiceBusClient and ServiceBusProcessor in this way:

processor.ProcessMessageAsync -= HandleEvent; // Is this needed?
await processor.DisposeAsync();
await serviceBusClient.DisposeAsync();

Do I need to remove the HandleEvent explicitly, or processor.DisposeAsync() should be responsible for that?

I cannot find that processor.DisposeAsync() is removing any handlers in its code, however, probably it is because removing the handlers is not needed at all? Official documentation seems also lacking any good examples of how to dispose instances of ServiceBusProcessor properly.

Can it be that await processor.DisposeAsync() is not needed at all, since serviceBusClient.DisposeAsync() should do all the job?

1 Answers

Can it be that await processor.DisposeAsync() is not needed at all, since serviceBusClient.DisposeAsync() should do all the job?

Yes await processor.DisposeAsync() is not needed, because calling either serviceBusClient.DisposeAsync() or CloseAsync should do all the job and will ensure that network resources and other unmanaged objects are properly cleaned up.

And also when a ServiceBusClient instance is disposed, it will automatically close and cleanup any senders, receivers, and processors that were created using it.

Related