Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi all,

I have extracted the Total frames of a video and saved in a Output Directory.
Now i have displayed all the farmes in a listbox on WPF window along with the frame no. on each frame.

C#
int FramesCount = 0;
List<stackpanel> splist = new List<stackpanel>();				
System.IO.DirectoryInfo myimagesdir = new System.IO.DirectoryInfo(@"E:\\tmp");
foreach(System.IO.FileInfo myimagesfile in myimagesdir.GetFiles("*.jpg"))
{
    FramesCount = FramesCount + 1;
    StackPanel sp = new StackPanel();
    sp.Height = 100; sp.Width = 125;			
									
    Image img = new Image();
    img.Height = 80; img.Width = 100;
    BitmapImage bitimg = new BitmapImage();
					
    bitimg.BeginInit();
    bitimg.UriSource = new Uri(myimagesfile.FullName);
    bitimg.CacheOption = BitmapCacheOption.OnLoad;
					
    bitimg.EndInit();
    img.Source = bitimg;
				
    TextBlock tb = new TextBlock();
    tb.Height = 20; tb.Width = 30; tb.FontSize = 15;
    tb.Text = FramesCount.ToString();
    sp.Children.Add(tb);					
    sp.Children.Add(img);
    splist.Add(sp);								
}
			
Frameslistbox.ItemsSource = splist;


Here for each file I am creating a stackpanel, image and textblock. image and textblock are added as children to stackpanel and this stackpanels are added to a list.

Now here every time new objects are created. How can i dispose the old objects in foreach loop?

Thanks
Posted
Updated 25-Oct-11 22:38pm
v5

For disposing object we can call the Dispose method or wrap the object with a using block.


In your case, you create BitmapImage, Image, TextBlock and StackPanel. None of these classes implement IDisposable. So, you don't need to dispose the objects, just remove them from the list (and then no one will have a reference to them), and the GC will free them.

 
Share this answer
 
Just as Shmuel Zang said, you don't need to care about that in the given context. You are creating some objects and put them in a list.
After the current iteration of the for loop is done, the holds the only references to your objects. And since the list is supposed to hold references to the objects, disposing them would not be a good idea.
If, some time later, the list throws its references away, the Garbage Collector will take care of the unreferenced objects.

As for the example: you can't create a new Image(); because Image is an abstract class. Instead you can directly
Image img = new Bitmap(myimagesfile.FullName);.
 
Share this answer
 
Before adding new objects iterate through spList children and dispose them one by one ,
and then add new children to spList.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900