Reputation: 2297
I have a Cache to store the most two recent images every time the user clicks the next image, Does the "RemoveAt(x)" dispose the x image, or what I want is for the removed image not to be in memory. to be totally removed.
List<Image> BackimageList = new List<Image>();
private void BackimageListCache(Image img)
{
BackimageList.Add(img);
if (BackimageList.Count > 2)
{
BackimageList.RemoveAt(0); //oldest image has index 0
}
}
Upvotes: 14
Views: 2712
Reputation: 133995
The RemoveAt
method does not call Dispose
on the image. You will have to dispose it yourself before you call RemoveAt
.
If the type implements IDisposable
, then to dispose it you write
BackImageList[0].Dispose();
BackImageList.RemoveAt(0);
RemoveAt(0)
does, essentially:
for (int i = 1; i < BackImageList.Count; ++i)
{
BackImageList[i-1] = BackImageList[i];
}
BackImageList.Count--;
That's all done internally, of course. You can't set the Count
property. It's done by the RemoveAt
method.
There is no need to set the value to null
before calling RemoveAt
.
Upvotes: 15
Reputation: 941525
Collections in .NET do not "own" an object. So they cannot assume that the object isn't used anywhere else, they can thus not dispose the object. Ownership rules are entirely your own to implement. Which does imply that you also have to be sure the the image isn't, say, displayed in a PictureBox.
Ensuring the image doesn't occupy any memory anymore is iffy as well. You cannot manage memory yourself, it is the job of the garbage collector. However, Image uses a rather substantial amount of unmanaged memory to store the pixel data, that memory does get released when you call Dispose(). The managed part of Image stays in memory until the GC gets to it. It is small.
Upvotes: 21