asgallant
asgallant

Reputation: 26340

Is Azure ServiceBus MessageSender class safe to run as a singleton in a long-lived process?

I have a long-running process that wakes up, performs some task, and may or may not need to publish a message via MessageSender to the Azure service bus. If I can make the MessageSender a singleton, that slightly simplifies my code, so I'd like to if it is viable.

To clarify, I expect that this process may go for very long periods of time (hours at least, potentially days) without sending any messages to the service bus.

Super-simplified example:

public async Task WorkLoop(CancellationToken token)
{
    while (!token.IsCancellationRequested)
    {
        var result = DoWork();
        if (result.shouldPublish)
        {
            var message = buildMessage(result);
            await _messageSender.SendAsync(message);
        }
        await Task.Delay(sleepDuration, token);
    }
}

Are there any consequences to keeping a MessageSender instance alive for a long time (days at least, possibly weeks or months)?

Upvotes: 4

Views: 1274

Answers (1)

devNull
devNull

Reputation: 4219

According to Best Practices for performance improvements using Service Bus Messaging:

It is recommended that you do not close messaging factories or queue, topic, and subscription clients after you send a message, and then re-create them when you send the next message. [...] You can safely use these client objects for concurrent asynchronous operations and from multiple threads.

Upvotes: 4

Related Questions