C# How to completely remove object from memory

Gerharddc picture Gerharddc · Jul 7, 2013 · Viewed 17.7k times · Source

I have a C# application consisting of a Pivot with multiple Pivotitems. The normal Pivotitems unload properly and do not leak memory. On two of the items though, I have Drawingsurfaces on which I use Monogame to render 3d models. Upon the unloading and loading of their pivots I am trying to completely destroy and then completely recreate the "Game" instances (mainly because Monogame does not allow you to draw to two surfaces at the moment and because they use a lot of memory and there is not enough for both of them).

My problem comes in that when I dispose the Xamlgame that is created upon loading it does not release all the memory it used. This means that every time I recreate the Xamlgame it just starts using more and more memory until there is no more left. Therefore, I would like to know if there is any C# way to completely dispose of all memory that was taken into use upon loading of an object.

Any Monogame specific way would also be appreciated. At the moment I am first disposing of my vertex and index buffer, then I clear my vertex and index lists, I then dispose of my Basiceffect and my Graphicsdevicemanager, I then call dispose on the "game" itself and finally I make the variable that contains the "game" equal to null.

PS. If you have ever done this in XNA then you might also be able to help me because the syntax is basically the same.

EDIT (Might be MonoGame bug):

I have now managed to clean all buffers etc. up properly. There is still a memory leak on my BasicEffect though. I have tried disposing it and making it null but no matter what it just keeps using more and more memory every time I reload my pivot.

Answer

Mostafa Soghandi picture Mostafa Soghandi · Jul 9, 2013

use garbage collector and wait to finalize it.

            GC.Collect();
            GC.WaitForPendingFinalizers();