Search code examples
c#azureazureservicebusservicebus

Check that TopicClient will work without error


I'm writing C# code which will send a message to the Azure ServiceBus thus (simplified for clarity):

private ITopicClient topicClient
 = new TopicClient(configuration["ServiceBusEndpoint"], configuration["ServiceBusTopic"]);

// test here

await topicClient.SendAsync(messageToSend.ToString());

What I'd like to do, if possible, is conduct some sort of test/check that the SendAsync() method is likely to have a good chance of succeeding before I call it, rather than have to catch any and all exceptions when it doesn't.

That is to say, that there is a valid, open connection to the ServiceBus, and it is ready to accept the message.

I can't find any info on how to do this from the various documents I've read online...

Has anyone else faced this situation? Thanks


Solution

  • While there's a property IsClosedOrClosing you could read to verify connection is still there, it is not going to remove the need to handle exceptions.

    Connection could die in the middle. Or you could get throttled. Or there could be a network glitch that would result in timeout. Or it could be a transient error where your code is expected to retry. There are plenty of exceptions that can take place and you need to handle those.

    In general, you want to look at the exceptions and determine if a retry is going to help (error is transient) or not. While the client has a retry policy built in, sometimes that's not enough. Especially when working with the Standard Tier where you could get throttled.