Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to completely remove object from memory

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.

like image 968
Gerharddc Avatar asked Jul 07 '13 06:07

Gerharddc


2 Answers

First you'll need to set the value to null so it is no longer in use:

 XamlGame = null

Then you can Activate the garbage collector:

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

If it does not dispose than either the XamlGame object is not null or a reference to it is still being held by another object.

Bear in mind that if XamlGame is inheriting from the Game class you won't be able to dispose it as it contain the running execution loop that keeps the entire game application alive. If you disposed it the application would crash and terminate.

like image 192
ChargerIIC Avatar answered Sep 24 '22 14:09

ChargerIIC


use garbage collector and wait to finalize it.

            GC.Collect();
            GC.WaitForPendingFinalizers();
like image 25
Mostafa Soghandi Avatar answered Sep 22 '22 14:09

Mostafa Soghandi