4
Answers

Need to release memory from unused images (Dispose?)

Hello,
I am making a game, and want to unload images when they aren't needed.
For now I am just setting their sources to null:
 
  1. imgExample.Source = null;  
 
But this isn't enough.
 
I already tried Freezing, but it doesn't seem to help much.
 
I read that their is such thing like "Dispose()" that seem to unload all the memory, in such cases, but I don't know how to use it.
 
I tried:
 
  1. imgExample.Dispose();  
 
But it didn't work, it seems I am missing either some kind of variable, or a using directive.
 
What can be done in this situation? 

Answers (4)

2
Photo of Amresh S
NA 528 4.2k 7y
Hi Evgenie,
 
You need to call the GC's finalizer to get the unrefreed-symbols from the cahe and this actually does the process to free the memoy. Refer the below code snippet:
 
  1. public class YourClass : IDisposable  
  2. {  
  3.     private bool disposed = false;  
  4.   
  5.     protected virtual void Dispose(bool disposing)  
  6.     {  
  7.         if (!disposed)  
  8.         {  
  9.             if (disposing)  
  10.             {  
  11.                 // Set Null values to your unused variables here
  12.             }
  13.             disposed = true;  
  14.         }  
  15.     }  
  16.   
  17.     public void Dispose() // Implement IDisposable  
  18.     {  
  19.         Dispose(true);  
  20.         GC.SuppressFinalize(this);  
  21.     }  
 Hope this helps.
 
Regards,
Amresh S. 
Accepted
2
Photo of Amresh S
NA 528 4.2k 7y
Hi @Evgenie,
 
Yes, thats enough to clear-up the memory used up. Also, you can specify the null vaues to any kind of return type variables in that part
 
//-set null vaues here.
 
Regards,
Amresh S. 
0
Photo of Evgenie Tivaniuk
NA 23 484 7y

@Amresh S

 
My many thanks, that worked perfectly! This reduced about 200M of RAM. God bless you! 
0
Photo of Evgenie Tivaniuk
NA 23 484 7y
I need to test it at home, but have a question for now.
 
About this line: 
 GC.SuppressFinalize(this);   
 
I am using GC.Collect in my code, can those two garbage collectors both work when used together?
 
And to make sure: 
I can use any kind of objects here, right? Except images I also have MediaElements. I guess that also works on them? So, all things I want to dispose, I need to put inside this? I can put them all here, together?
 
Sorry if my questions are silly. 
 
 
  1. if (disposing)
  2. {
  3. // Set Null values to your unused variables here
  4. }