Closing the Connection

Both Cluster and Cluster objects implement the IDisposable pattern and also have finalizers. That being said, managing the lifetime of these objects is critical for developing robust, high performance applications. In a typical application, you would create a single, static Cluster object that would live the duration of the application or process’s lifetime - create the Cluster object when the application starts and call it’s Dispose method when the application shuts down. Depending upon finalization is not suggested, but admissible in certain applications.

You can close a bucket and release the internal connections by using one of the following methods:

  • Through finalization and garbage collection (GC)
  • Calling Dispose explicitly or implicitly via the using statement
  • By calling Cluster.CloseBucket() and passing the bucket reference

Using finalization and garbage collection is the least dependable method and relies on a certain amount of nondeterminism because you are relying on the common language runtime (CLR) finalization mechanism; just let the object go out of scope. The other methods are preferred because you deterministically control the object's lifetime. Here is an example that uses the Cluster.CloseBucket() method:


  using (var cluster = new Cluster(config))
  {
      IBucket bucket = null;
      try
      {
          bucket = cluster.OpenBucket();
          //use the bucket here
      }
      finally
      {
          if (bucket != null)
          {
              cluster.CloseBucket(bucket);
          }
      }
  }
		
Note: It’s important to know that the references to the CouchbaseBucket (or MemcachedBucket) are reference counted because multiple threads might be using the same object. If multiple threads are using the bucket and each calls either Cluster.CloseBucket() or Dispose() (either implicitly through the using statement explicitly), the instance will not be disposed until the reference count reaches zero.