Home > Mobile >  Consuming an AMQ queue in a BackgroundService
Consuming an AMQ queue in a BackgroundService

Time:12-02

I have an ASP.Net Core Web API application which consumes messages from an AMQ Queue. Currently I have the consuming code in a BackgroundService with an event handler hooked up to the Listener. The whole thing is in a while look (checking the cancellation token) to ensure any errors are handled and we retry the subscription but I also have an inner while loop to keep the service alive but it doesn't need to do anything.

My question is, what should I do inside that inner while loop to make sure I don't consume unnecessary CPU; e.g. Task.Yield(), Task.Delay(something)?

public class ReceiverService : BackgroundService
{
    ...

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        ...
        
        while (!stoppingToken.IsCancellationRequested)
        {

            ...

            IConnectionFactory factory =
                new NMSConnectionFactory(
                    $"activemq:ssl://{parsed?["message"]}:51513?wireFormat.maxInactivityDuration=0");

            connection = await factory.CreateConnectionAsync(Username, Password);
            var session = await connection.CreateSessionAsync();

            var destination = await session.GetQueueAsync("queuename/"   subscriptionId);
            var consumer = await session.CreateConsumerAsync(destination);
            consumer.Listener  = async message =>
            {
                // do stuff with message
                message.Acknowledge();
            };

            while (!stoppingToken.IsCancellationRequested)
            {
                await Task.Delay(0, stoppingToken);
            }

            await connection?.CloseAsync()!;
            await Task.Delay(1000, stoppingToken);
        }
    }
}

Cheers

Rich

CodePudding user response:

If you have nothing but cleanup to do, then you can just do await Task.Delay(Timeout.InfiniteTimeSpan, stoppingToken);. No need for any loops at all.

  • Related