Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RemoveAt(x); Does it dispose the element x?

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
   }
}
like image 431
electricalbah Avatar asked Apr 24 '13 01:04

electricalbah


People also ask

How Does RemoveAt work?

When you call RemoveAt to remove an item, the remaining items in the list are renumbered to replace the removed item. For example, if you remove the item at index 3, the item at index 4 is moved to the 3 position. In addition, the number of items in the list (as represented by the Count property) is reduced by 1.

How to use RemoveAt in vb net?

removeAt takes index as parameter while remove take item as parameter. RemoveAt is faster as it directly worked over an index and perform operation while remove check all indexes to find matching item.


2 Answers

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.

like image 51
Hans Passant Avatar answered Sep 24 '22 06:09

Hans Passant


The RemoveAt method does not call Dispose on the image. You will have to dispose it yourself before you call RemoveAt.

Edit

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.

like image 40
Jim Mischel Avatar answered Sep 23 '22 06:09

Jim Mischel