title: How to gracefully disconnect from rabbitmq queue
body: <p>I am experiencing a racing condition issue with my rabbitmq client. My service has multiple instances listening on a single queue, storing received messages into a db. </p>
  
  <p>When they all get restarted at once, i sometimes see messages being redelivered and stored in the db twice. This is normally handled on client side by checking if the correlationid has already been stored in the db. This works 99.9% of the time (i am processing 5mill messages a day, it happens once or twice a day).</p>
  
  <p>So as i said, i suspect a racing condition being responsible for this. I think i receive the message again while my first message is still being processed. So when i check i dont see it stored in the db, and in the end, store it twice.</p>
  
  <p>I should not that this is a non-issue, but has been bothering me because i can't really explain what happens.</p>
  
  <p>I suspect that it happens when i restart the services. I think i disconnect from the queue, while i am still processing the message, triggering rabbitmq to redeliver again to another instance that is not shutdown yet. </p>
  
  <p>What i want to do is when i am stopping the service is to </p>
  
  <ul>
  <li>tell rabbitmq that i dont want to receive further messages</li>
  <li>wait for all currently processing messages to finish</li>
  <li>send acks / nacks</li>
  <li>shutdown</li>
  </ul>
  
  <p>Right now i am first deregistering the received event</p>
  
  <pre><code>_consumerServer.Received -= MessageReceived;
  </code></pre>
  
  <p>then i am disposing the channel and the server</p>
  
  <pre><code>        if (_channel != null)
          {
              _channel.Close();
              _channel.Dispose();
          }
  
          if (_connectionServer != null)
          {
              _connectionServer.Close();
              _connectionServer.Dispose();
          }
  </code></pre>