Is it a good practice to re-create a Topic Client before sending a message to Azure Topic

1.3k Views Asked by At

I am using Microsoft.Azure.ServiceBus, Version=2.0.0.0 assembly to connect to Azure Topics. The code is below

public void SendMessage(Message brokeredMessage) 
{
    var topicClient = new TopicClient(_configuration.ConnectionString, topicName, _defaultRetryPolicy);
    await topicClient.SendAsync(brokeredMessage);
    await topicClient.CloseAsync();
}

I was wondering whether it's a good practice to create the Topic Client every time I need to send a message to the topic, or should I create the Topic Client on application startup and keep using the same client every time I need to send a message?

Are there any performance or scalability issues that I need to consider?

1

There are 1 best solutions below

0
On BEST ANSWER

From Azure Service Bus Best Practices post:

Reusing factories and clients

Service Bus client objects, such as QueueClient or MessageSender, are created through a MessagingFactory object, which also provides internal management of connections. You should 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. Closing a messaging factory deletes the connection to the Service Bus service, and a new connection is established when recreating the factory. Establishing a connection is an expensive operation that you can avoid by re-using the same factory and client objects for multiple operations. You can safely use the QueueClient object for sending messages from concurrent asynchronous operations and multiple threads.

Based on this, you should be reusing the Topic Client object.