Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispose on nested Disposable items?

I wanted to know if there are any conventions regarding disposal of disposable items nested inside another disposable item(in a property/public field, not as private members). For example, a DataSet contains DataTable(s) and a SqlCommand contains a SqlConnection.

The obvious thing would be for a class to dispose of all Disposable items it owns, and leave the rest. Does there exist such a convention? If it does, how does .NET libraries determine who owns what? How can I find out whether nested objects are being disposed?

PS: I have been wondering about this for a while, and apparently so have others : What gets disposed when SqlCommand.Dispose is called?

Edit 1 : Found out that disposing DataSet, does not dispose its tables.

// Fill dataset from sqldataadpater.
foreach (DataTable dt in dataSet.Tables)
{
    dt.Disposed += Program.DisposedEventHandler2;
}
Console.WriteLine("Disposing dataset");
dataSet.Dispose(); //Event not fired here.
Console.WriteLine("Disposing datatables maually");
foreach (DataTable dt in dataSet.Tables)
{
    dt.Dispose(); //Event fired here
}
#endregion
like image 930
apoorv020 Avatar asked Jul 22 '10 06:07

apoorv020


1 Answers

The rule of thumb I normally follow is that the class that creates a disposable object, will also dispose it. As an example: a SqlCommand does not dispose its connection, because it didn't create it. The StreamReader has a strange behavior in this sense, because it will always dispose the underlying stream, even if it is supplied from the outside (I find this very annoying, please vote HERE when you like Microsoft to fix this).

like image 80
Steven Avatar answered Oct 20 '22 00:10

Steven