marți, 13 aprilie 2010

Disposable generic list members

In this short post I will discuss about the necessity of calling Dispose on Disposable generic list members prior to remove them from the list.
Say you have a disposable type, e.g. MyDisposableType and create a generic list of such a type:

List myList = new List( );

Now, suppose that you use your list and at some point you need to remove one of the items using RemoveAt. With disposable types, the correct sequence should be:

myList[ itemIndex ].Dispose( );
myList.RemoveAt( itemIndex );

and this is because instances of non-disposed objects that are referred by MyDisposableType would still exist in memory after the object reference is removed from the list.
This is easy to verify using the .NET CF Remote Perfomance Monitor and taking GC Heap snapshots and monitoring the instance numbers of Disposable types referred by MyDisposableType.

Niciun comentariu:

Trimiteți un comentariu