title: Service Bus Disposed Object
body: <p>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:</p>
  
  <p>Sometimes I get this message</p>
  
  <pre><code>Message:Can't create session when the connection is closing. 
  </code></pre>
  
  <p>Other times i get this message</p>
  
  <pre><code>Message:Cannot access a disposed object.
  Object name: 'FaultTolerantAmqpObject`1'. 
  </code></pre>
  
  <p>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</p>
  
  <p>Here is my code</p>
  
  <pre><code>Task.Run(() =&gt; new ServiceBusService().SendQueueMessage(busMessageObject));
  </code></pre>
  
  <p>ServiceBus Class</p>
  
  <pre><code>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);
              }
          }
  }
  </code></pre>