Search code examples
.netdatasetstrongly-typed-datasettableadapter

Is there any reason to dispose of a table adapter?


In many cases when working with different types of data objects it's important to dispose of them to make sure that they don't leave a database connection open. However, table adapters don't seem vulnerable to this problem because they are built on the principle of disconnected data. I am under the impression that a table adapter will always close it's connection after the atomic Fill or Update method has completed, even in the presence of exceptions. Is this correct?

On the other hand, table adapters do implement IDisposable, so there must be some unmanaged resources to clean up at some point, right? Or is this just ceremony so that people can write:

using(var a = new MyTableTableAdapter())
{
    a.Fill(ds.MyTable);
}

and not have to think about this topic?


Solution

  • If it implements IDisposable it either currently holds resources to dispose of or may in the future. If it's disposable, you should dispose it. It's not for you to understand it's internals - only to understand it's contract and honor it. Typically, folks don't do things out of ceremony - "using" is cool syntactical sugar but not cool enough to start sprinkling IDisposable around classes that don't have resource to dispose of :)

    Also, IDisposable doesn't necessarily mean "unmanaged" resources. It means there are resources (like file handles, network connections etc...) that are not objects that are garbage collected (memory). The distinction is cleaning up something not collected - not unmanaged. It just so happens that often many of those resources are backed by unmanaged OS resources.

    EDIT:

    For example, let's say I created a completely managed object that retrieved some other objects from a pool (cache) on demand and when you're done using it, I want it to put those objects back into the shared pool (not freed - an explicit call to add something to a pool. Nothing unmanaged here but I could pull objects from the pool on demand and in dispose I could put them back (Pool.Add) for others to use. You the consumer would simply "use" my object and know it will clean up when disposed. The explicit dispose is needed because we shouldn't wait for finalize (it may happen way later or not at all) –