Search code examples
c#.netrabbitmqamqprabbitmq-exchange

Delete RabbitMQ Queue when Application is closed abnormally


I am using .NET RabbitMQ Client library. I want to develop a messaging system. For this, I have implemented all necessary methods of RabbitMQ. Moreover I have developed dispose() for deleting queue. I am calling this method in FormClosing event so this method will be triggered when user closes the application by clicking on close button and by the logic queue will be deleted. Up to this, all code is working perfectly.

But my problem is

I'm not able to delete a queue at the time of closing the application without clicking on close button (let's just say closing application from task manager or from command prompt using taskkill command or any abnormally reasons) as this dispose() will not be triggered. At this time, queue will not be deleted until I delete it from management portal manually.

So my question is,

How can I know that the application is closed and that orphan queue can be deleted?


Solution

  • RabbitMQ exposes a REST based management API which enables you to handle queue creation / deletion.

    What you could do is have your application query that management API on startup to see if any queues were left abandoned because of previous unexpected shutdown, or you could have a completely different service which is responsible to do that (it's a design choice).

    You can query your management API via EasyNetQ Management API:

    managementClient.DeleteQueue(queue);
    

    You can find the full documentation here.

    Edit:

    After doing some reading, perhaps an Exclusive or Auto-Delete queue will suffice?

    Exclusive (used by only one connection and the queue will be deleted when that connection closes)

    Auto-delete (queue is deleted when last consumer unsubscribes)