A newer version of this documentation is available.

View Latest

Closing the connection

Both Cluster and IBucket objects implement the IDisposable pattern and also have finalizers.

Managing the lifetime of the objects Cluster and IBucket is critical for developing robust, high performance applications. In a typical application, you would create a single, static Cluster object that would live for the duration of the application or the 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.

Closing the bucket

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;
          bucket = cluster.OpenBucket();
          //use the bucket here
          if (bucket != null)
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 Cluster.CloseBucket() or Dispose(), either implicitly through the using statement or explicitly, the instance will not be disposed until the reference count reaches zero.