EK_AllDay
EK_AllDay

Reputation: 1115

Service Bus Disposed Object

I am using message queue architecture on Azure through Service Bus. Occasionally when I attempt to send a message to the queue it fails. Here is the Error I get:

Sometimes I get this message

Message:Can't create session when the connection is closing. 

Other times i get this message

Message:Cannot access a disposed object.
Object name: 'FaultTolerantAmqpObject`1'. 

Keep in mind that it doesnt happen all the time. Sometimes I am creating thousands of messages for the service buss. I am dispatching an async task for each message I send to the queue

Here is my code

Task.Run(() => new ServiceBusService().SendQueueMessage(busMessageObject));

ServiceBus Class

public class ServiceBusService
{ 
    static string ServiceBusConnectionString = AzureUtils.SERVICE_BUS_CONNECTIONSTRING;
    const string QueueName = "eventqueue";
    static IQueueClient queueClient;

    public async Task SendQueueMessage(JObject jObject, DateTime? scheduledEnqueueTimeUtc = null)
    {
        string jsonObject = "";
        string scheduledTime = "";

        if(scheduledEnqueueTimeUtc.HasValue)
        {
            scheduledTime = scheduledEnqueueTimeUtc.Value.ToLongTimeString();
        }

        try
        {
            queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
            var message = new Message(Encoding.UTF8.GetBytes(jObject.ToString()));

            if(scheduledEnqueueTimeUtc.HasValue)
                message.ScheduledEnqueueTimeUtc = scheduledEnqueueTimeUtc.Value;

            await queueClient.SendAsync(message);
            await queueClient.CloseAsync();
        }
        catch (Exception e)
        {
            Trace.TraceError($"{Tag()} " + e.InnerException + " " + e.Message);
        }
    }
}

Upvotes: 4

Views: 6617

Answers (1)

EK_AllDay
EK_AllDay

Reputation: 1115

It was because my QueueClient was static and multiple threads were using it, and disposing it. Making it not static solved my issue.

Upvotes: 5

Related Questions