Click here to Skip to main content
15,887,256 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
We all love the C#'s garbage collector. I know, It's perfectly great for 99.999% of application etc...

I was wondering however if it would be possible in any way to manually destroy an object in C#, as I can in C++. What I mean is that it's memory will be freed, (of course providing there are no references to it), as if the GC has collected that object.

Is that achievable in C#, or is there an interesting "hack" that can enable such activity?
Posted
Updated 13-Jul-15 23:05pm
v2
Comments
F-ES Sitecore 14-Jul-15 5:47am    
If you want to manage your own memory use C++. One of the concepts of a framework like .net is that it manages these things for you so that you don't screw up and destabilise the whole system.

It's a good question! However I'am afraid there is no straightforward methodology.

Theoretically, the GC uses the Win32 VirtualAlloc function to reserves a segment of memory, and releases segments back to the operating system (after clearing them of any objects) by calling the Win32 VirtualFree function. So if you want to go ahead and try to manage the segments yourself, you'll have to put so much effort in it, that I'll bet it will surpass the dev time of your whole project...
 
Share this answer
 
As far as I know all housekeeping operations go via garbage collector. So the closest thing that comes to mind is to call the Collect method. See GC.Collect Method[^]

However, it should be needed in very rare occasions since the framework tries to keep enough free memory available.
 
Share this answer
 
Comments
Jo Mua`mar 14-Jul-15 4:54am    
Hi Mika, tx for the answer, however, calling the GC.Collect is not what I was looking for, firstly, it does not ensure that the GC will actually collect when you requested. Secondly, even if it does, the full collect action has implications, such as, "promoting" objects from generation 0 to 1, 1 to 2 etc which is an interference I don't want in the activity of the GC
Wendelius 14-Jul-15 5:11am    
Very good points and as I said Collect was what came to mind. But I agree it isn't really destroying objects as you would like.
There is a way to destroy the object in memory as follow.
1. GC.Collect.
2. IDisposable interface.

For memory reclaim we can use both of this but when we use GC.collect in c# application is called bad way implementation

IDisposable is a good way to destroy the object in memory.
 
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