tags:

views:

417

answers:

7

I am fairly new to learning C# (from Java & C++ background) and I have a question about manual gargabe disposal: is it even possible to manually destroy an object in C#? I know about the IDisposable interface, but suppose I'm dealing with a class I didn't write and it doesn't implement it? It wouldn't have a .Dispose() method, so that and using { } is out, and .Finalize is always either protected or private so that's not an option either.

(I am just trying to learn what is possible in C# in this case. I suppose if all else fails I could inherit the hypothetical ImNotDisposable class so that it does implement IDisposable.)

+5  A: 

If the object is not reachable then you can call GC.Collect() and the object will be destroyed. The concept of IDisposable has nothing to do with the CLR and is mostly for user code to implement to perform additional disposal logic. Calling Dispose() on an object will not free the object itself from memory, though it may very well dispose any resources that this object references.

I should add that while what I said is a way to achieve this, in 99.9999% of applications you should never call GC.Collect() because it'll often degrade the performance of your application instead of improving it.

Eilon
calling `GC.Collect()` isn't something you should do, unless it's for a *very* good reason.
Sander Rijken
to add to this, it will only collect the object if there are no more references to that object.
McAden
It's not about references to the object - it's about reachability (which I do mention).
Eilon
What is the difference between an object that has no references and an object that is no longer reachable?
Justin R.
If object a has a reference to object b, and b has a reference to a, then both of a and b are referenced (AKA a circular reference). However, if no one else has a reference to either a or b, then neither is reachable, and the garbage collector will destroy them (eventually).
Eilon
Can a single, occasional call to `GC.Collect()` spaced some minutes apart in time actually hurt performance?
Cecil Has a Name
Time plays no part in GC performance. It's all about how often and how much memory is allocated. The fact that you space the calls minutes apart means nothing - if a normally induced GC would not have occurred then you may be unnecessarily promoting objects into higher generations which affects performance. Particularly in long running applications and services.
Josh Einstein
@Cecil: YES, it can hurt performance. Imagine forcing a your main thread to stop for a collection even when there's nothing to collect, or forcing a collection when your app is busy. Even worse, because the garbage collector is generational you can force objects to move into a longer living generation that really should not do so.
Joel Coehoorn
A: 

No, you can't destroy a specific object.

It is possible to invoke the garbage collector, which will look for objects to destroy, but it's almost never a good idea.

Jay Bazuzi
+4  A: 

You don't manually destroy .net objects. That's what being a managed language is all about.

What you can do is call GC.Collect() to force a general collection. However, this almost never a good idea and you can't make it target your specific object. In fact, if you still have a reference to this object that you could use to tell it which object to target I can promise you that it won't be collected.

Instead, it's probably better to simply pretend that any object that doesn't use unmanaged resources and is not reachable by any other object in your program is immediately destroyed. I know this doesn't happen, but at this point the object is just a block of memory like any other. You can't reclaim it and it will eventually be collected, so it may just as well be dead to you.

One final note about IDisposable. You should only use it for types that wrap unmanaged resources: things like sockets, database connections, gdi objects, etc.

Joel Coehoorn
I also use dispose to unlink any events I've hooked up to external objects. If you don't do this the object will not be removed from memory until the external object is, which could be for the lifetime of the application.
Mongus Pong
A: 

You can force the garbage collector to run after the variable you want to destroy goes out of scope, but you normally don't want to do that, as the garbage collector is more efficient if left to do its own work.

Forcing garbage collection can be done with GC.Collect, but don't do it. In my 10 years as a .NET developer, I have never needed it.

Mark Seemann
A: 

It's not possible to destroy an object in a deterministic fashion. The CLR determines when the flagged object is reclaimed. This means that while you can flag an object for reclamation and ensure that managed and unmanaged resources are tidied up for disposal (by implementing the IDisposable pattern), the actual time the memory is released is up to the CLR. This is different from C++ where you could actually delete something and it would be released then.

Happy coding,

Scott

Scott Davies
Calling dispose doesn't flag the object as reclaimable, it just allows you to release limited resources like database connections as soon as you're done with them rather than waiting for the garbage collector to come and decide it's time to finalise the object.
Paolo
+1  A: 

You can't manually destroy an object "like C++ delete", all what you can do is just close any exclusive resources the object has acquired and null all references to this object, so the GC can collect it, also don't call GC.Collect() by yourself, the GC process is expensive, as it has to suspend all other threads to safely collect the objects from memory, so just trust the GC, and it will kick off when needed.

bashmohandes
Well I wouldn't ever actually assign any reference variables to a null value like myObj = null; I'd just allow them to go out of scope.
East of Nowhere
I agree, I would rather try to do this if possible
bashmohandes
+2  A: 

Although you can trigger garbage collection (you need to trigger GC for all generations because you can't be sure which generation the finalizable object is in) you cannot necessarily force finalization of a particular object. You can only depend upon assumptions about how the garbage collector works.

Furtnermore, since finalization happens on its own thread, you should call WaitForPendingFinalizers after triggering garbage collection.

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

As was noted by others, this can actually hurt your application's performance because unnecessarily invoking the GC can promote otherwise short-lived objects into higher generations which are more expensive to collect and are collected less frequently.

Generally speaking, a class that implements a finalizer (destructor) and does not implement IDisposable is frowned upon. And anything that implements IDisposable should be calling it's finalizer logic and supressing itself from finalization at garbage collection.

Jeff Richter recently posted a nice little trick for receiving a notification when garbage collection occurs.

Another great article on Garbage Collector Basics and Performance Hints by Rico Mariani (MSFT)

Josh Einstein