How GC releases managed resources in C# - c#

As of my knowledge i know like GC performs collection operation in order to remove unmanaged resources to release memory which is called implicit clean up. And by using 'USING' keyword we can do it explicit cleaning but my doubt is how GC releases managed resources.

You don't have to do anything special in order for GC to clean up your managed resources. GC will clean it up sometime after there are no references left to your managed resource.
If your managed resource owns unmanaged resources, you can implement the IDisposable interface and call the Dispose method, in which you'd explicitly clean up your unmanaged resources. using statement makes it very easy to use this interface, as it automatically calls Dispose when the code exists the using block, even in case of exceptions.
You might take a look at the MSDN documentation on Garbage Collection.
EDIT: based on comments above.
You could override Object.Finalize by defining a finalizer (e.g. ~MyClass()) but there is no telling when it will be called by GC. IDisposable is generally preferred. More info on Finalizer vs Dispose here.

Related

In C# does (new Obj()).foo() dispose of Obj when the parenthesis scope is exited?

I am happy using IDisposable and using blocks but often I find myself writing (new Obj()).Foo(); to avoid the extra instantiation code and naming etc. Does this instance hang in memory until the end of the function scope or is it disposed of directly after the enclosing parenthesis is exited...? Is there an alternative I am missing? An equivalent to implementing IDisposable for concrete objects that I want to use once and throw away?
IDisposable is not related whit when the memory allocated for the object is released. In both cases the memory is released when the Garbage Collector decides to release it.
IDisposable is used for objects that need to execute some action in order to release the resources it allocates outside them. For example if the objects open a Database connection, you must release it as soon as you don't need it anymore.
So IDisposable gives you one thing:
A way to release the resources as soon as you want, by calling the Dispose() method or using the using clause
So it's ok to do:
new Obj()).Foo();
And has no sense to make Obj implements IDisposable if it does not uses any resource that must be deallocated.
If an object implements IDisposable, it is imperative that you Dispose() the object in your own code, either explicitly (and within a try/finally construct, too!) or with the using syntax, and do not simply let the reference(s) fall out of scope.
EDIT: I feel like I used an awful lot of words to get around to explaining the most important aspect of all this, which is that the only reason an object should implement IDisposable is if it holds handles to other objects that are unmanaged (the CLR doesn't know about them) or scarce (due to resources/cost/licensing/etc.). So if an object implements IDisposable, you MUST call Dispose() YOURSELF, as soon as possible. The CLR will not do it for you. And if you implement IDisposable on your own classes, you need to be implementing a finalizer on them, too.
Simply letting a reference fall out of scope does not cause the GC to run immediately, and you have no guarantees whatsoever that a GC is going to occur any time soon. You can explicitly trigger a GC with code, but that is typically going to hurt overall performance more than help it.
If there is not much memory pressure, for instance, the CLR may wait a long time before running the GC. There just isn't a pressing need for it to run in a situation where there is light or zero contention for resources. If it ran too often, it would impact the performance of your applications negatively
The GC does not call Dispose(). The GC calls an object's finalizer if it has one. The finalizer is a special method using syntax similar to a C++ destructor, but which really is not a destructor in that sense.
So if an object implements IDisposable, but does not implement a finalizer, the GC will never release that object's resources. The object will cause both memory leaks and unresolvable resource contention.
Nor does calling Dispose() from your own code trigger a GC.
The finalizer is a last-ditch backup mechanism to try to ensure that a class holding scarce or expensive resources does eventually let go of them even if consumers of the class fail to explicitly release those resources.
IDisposable is really just a common convention, implemented with a handy well-known interface contract, to let callers generically request that any class holding scarce resources release those resources immediately.
The standard pattern is that the finalizer calls the Dispose() method (actually, it typically calls Dispose(false) and I'm intentionally ignoring that detail). The Dispose() method will release all the scarce resources, then it can call GC.SuppressFinalize() so that the GC can free the object's memory more quickly when it gets around to running.
The old tried and true "acquire late/release early" semantics apply here.
You should read up on how the GC uses multiple passes or "generations" to clean up objects with finalizers.
The GC can get rid of regular objects (objects where all the resources are managed by the CLR) in one pass. If there are no in-scope references to an object, the GC can basically just delete it.
But if an object has a finalizer (and GC.SuppressFinalize() has not been called), the GC uses at least 2 passes or generations to release the object. In the first generation, it marks the object for finalization. In the second generation (which happens the next time the GC runs), it actually calls the finalizer, and at that point the object is finally eligible to have its memory released.
The scarce/expensive resources we're talking about are typically things like network sockets, file handles, database or other server connections which may be limited or expensive or resource-intensive or all three, etc. This is also true of virtually all "unmanaged" (non .NET CLR) resources, including things like Win32 window handles, file handles, network sockets and so on. Such resources require deterministic cleanup. You need to let go of them as quick as you can, but the CLR is going to take its sweet time getting around to cleaning this stuff up. You have to do it yourself.
But if your class isn't using any of these types of scarce/expensive/"unmanaged" resources, then there is probably no reason to implement IDisposable on it at all.

Are non-disposed resources freed when an object is garbage collected?

I was posed this question, and while I believe I know the answer, I believe I should be 100% certain else I start spreading misinformation!
I have this object:
public class MyObj(){
private SqlConnection conn;
public MyObj(string connString){
var stream = File.Open(#"c:\\file.txt");
conn = new SqlConnection(connString);
}
}
When this object is created, a file handle is associated with the file, and a connection to a database is created. Neither has Dispose called on it as they should.
When this object goes out of scope and is eventually garbage collected, are these two resources then released, or do they remain in memory?
When this object goes out of scope and is eventually garbage collected, are these two resources then released, or do they remain in memory?
Usually some type - often somewhat hidden from the public API - has a handle on a native resource, possibly via SafeHandle, and that's what ends up releasing the resource. It's possible to write code which doesn't do this, of course, in which case the native resources would only be released on process exit through the normal OS clean-up, but I'd expect any Microsoft-provided APIs to do the right thing.
Of course, you should still dispose of resources explicitly :)
Any object that directly uses an unmanaged resource like a file handle or a database connection should always implement a finalizer that releases the unmanaged resource. When the object is garbage collected the finalizer is executed and the unmanaged resource is freed. So to answer your question:
When this object goes out of scope and is eventually garbage collected, are these two resources then released, or do they remain in memory?
Yes, the unmanaged resources will eventually be freed by the garbage collector that calls the finalizer of the object.
As you are aware of, leaving it to the garbage collector to clean up unmanaged resources is normally a bad thing. If you open and read a file you would prefer that the file is closed and available to other processes when the read has completed instead at some random future time when the garbage collector decides to release the now unused file object.
.NET provides the IDisposable interface to enable deterministic release of unmanaged resources. When you dispose a FileStream object the underlying unmanaged file handle is released and the file is closed.
An important part of implementing the IDisposable interface is that if the unmanaged resource is released via a call to Dispose then the object no longer needs to be finalized. That is why you see a call to GC.SuppressFinalize(this) when an object implements IDisposable and has a finalizer. Avoiding finalization is a good thing to reduce the amount of resources that the garbage collector has to use. Also, finalizers run within tight constraints established by the garbage collector so they are best avoided.
Note that most of the time your objects will not have a finalizer because you do not use any unmanaged resource. Instead you will get access to unmanaged resources using a managed objects like SafeHandle. In that case the object does not need a finalizer but should implement IDisposable and forward calls to Dispose to any aggregated IDisposable objects.
Short answer: They are automatic released.
Just one time, years ago, I got a inexplicable memory leak due to a object not being released.
At the time I need to put some explicit call to the garbage collector to fix the problem.
Never found the real cause, maybe a framework bug, maybe something to do with a OS resource but I can say 99.99% of time you can be free of worries about it in C#.

IDisposable and managed resources [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Proper use of the IDisposable interface
I have a class that has both managed and unmanaged resources. I am using IDisposable to release un-managed resources. Should I release managed resources in the dispose method? Or I can leave it to GC to release managed resources?
If you have a look at the following documentation you will find the line:
Free any disposable resources a type owns in its Dispose method.
So in your dispose method you should dispose of managed resources that also implement IDisposable. If an object doesn't implement this, you don't have to dispose of it.
I would suggest that classes with finalizers (the C# compiler generates finalizers for any classes with destructors) should avoid holding references to any objects that won't be used in finalization. With relatively few exceptions, classes which hold resources that are encapsulated in objects should avoid holding resources that are not so encapsulated. Instead, those resources should be encapsulated into their own objects, so they can be held along with the other resource-containing objects.
Once that has been taken care of, the proper behavior for any class which owns resources that are encapsulated in other objects is generally to call Dispose on all such resources within its own Dispose method, and not to implement a finalizer (and--for C#--not to have a destructor, which would cause the compiler to generate a finalizer). If the finalizer runs on an object which holds other finalizable objects, each of those objects will usually be in one of three states:
The finalizer on that other object will have already run, in which case it's not necessary to do anything to clean it up.
The finalizer on that other object will be scheduled to run, in which case it's probably not necessary to do anything to clean it up.
Other strong references may exist to that other object, in which case it shouldn't be cleaned up yet.
Only in the second case would there be any reason to think about doing any cleanup on the other object.
Note, btw, that the garbage collector should almost never be relied upon to do anything other than free up memory directly consumed by object instances. Deterministic disposal is almost always much better. The only times one should ever deliberately use the garbage collector to clean up resources is when one is going to be creating relatively-low-cost resources which are known to clean themselves up effectively when garbage-collected, and the instances will be widely-enough shared that finding out when the last one leaves scope would otherwise be impractical. Although there is sometimes good justification for abandoning disposable objects, abandoning disposable objects without justification is always a mistake (if it's appropriate to abandon disposable objects, it's appropriate to justify one's reasons for doing so).

What are the kind of variables that must be disposed? (.NET/Java)

Three questions:
What kind of variables should be disposed manually in .NET/Java? I know that SqlConnection should always be either disposed manually or used in a using{} block. Is it right? What are the other kind of variables that should be disposed?
I read somewhere that unmanaged code must be disposed manually. Is that right? What exactly is unmanaged code and how do I know if a variable is managed or unmanaged?
Finally, how do I dispose variables? I know that the Dispose() method does not really dispose a variable. So what does Dispose() do? Should I set them to null()? What is the logic by which the garbage collector works?
This answer deals only with the .NET part of your question
What kind of variables should be disposed manually in .NET/Java? I know
that SqlConnection should always be
either disposed manually or used in a
using{} block. Is it right? What are
the other kind of variables that
should be disposed?
In .NET, all objects that implement IDisposable should be disposed explicitly (or used in a using block).
I read somewhere that unmanaged code must be disposed manually. Is
that right? What exactly is unmanaged
code and how do I know if a variable
is managed or unmanaged?
You probably mean unmanaged resources, as code can't be disposed... All classes that use unmanaged resources (memory allocated not on the managed heap, win32 handles...) should implement IDisposable, and should be disposed explictly, since they are not managed by the garbage collector.
Finally, how do I dispose variables? I know that the Dispose()
method does not really dispose a
variable. So what does Dispose() do?
Should I set them to null()? What is
the logic by which the garbage
collector works?
I'm not sure I understand your question... you don't dispose a variable, it is managed by the garbage collector. All managed memory is automatically released when it's not used anymore (i.e. it is not accessible by code because there are no references left to it). The IDisposable.Dispose method is only intended for resources that are not managed by the GC.
EDIT: as a side note, I would like to add that IDisposable is primarily intended to clean-up unmanaged resources, but is also frequently used to perform other cleanup actions and guarantee state or data integrity. For instance, IDbTransaction implements IDisposable in order to rollback the transaction if an exception occurs before the transaction was committed :
using (var trx = connection.BeginTransaction())
{
// Do some work in the transaction
...
// Commit
trx.Commit();
} // the transaction is implicitly rolled back when Dispose is called
In Java, you "close" rather than "dispose".
JDBC Connections, unless you got them from a pool.
JDBC ResultSets, depending on the JDBC connector.
InputStreams, OutputStreams, Readers and Writers (with the exception of those that are byte array and string backed).
Some third-party Java libraries or frameworks have classes that need to be manually disposed / closed / destroyed.
.NET
All objects that implement the IDisposable interface are asking that their Dispose methods are called when they are no longer required. The using block is just C# sugar for a try-finally block that disposes the IDiposable in the finally block, as long as it is not null. Consequently, disposal occurs even if an exception is thrown in the try block.
Unmanaged Code.
The Dispose method does whatever code the developer who wrote the Dispose method put in it! Typically this involves releasing 'unmanaged' resources, which are not managed by the runtime, such as database connections, window handles and file handles. Note that the GC manages the heap, so setting a reference to null just before the object it references becomes unreachable doesn't help all that much.
This is a good read.
This was mostly covered by Thomas, but to expand on the third point:
Finally, how do I dispose variables? I know that the Dispose()
method does not really dispose a
variable. So what does Dispose() do?
Should I set them to null()? What is
the logic by which the garbage
collector works?
They key is that the Dispose() tells the object to free any unmanaged resources that it currently holds, it does not free the object itself.
The garbage collector knows how to free the object, but for IDisposable objects, only the object itself knows how to dispose of it's private resources, so you have to make sure that Dispose() gets called before the garbage collector frees the object.
For Java:
SWT is a framework where we have to dispose resources (like images), because the framework uses native libs and system handles which have to released. SWT classes are documented and tell, when dispose is required.
Following up on other .NET solutions...
If your object owns unmanaged resources, it's not enough to simply clean them up on Dispose() calls, because you have no guarantee that Dispose will get called. The full solution is:
Add a finalizer for the class.
Add a public bool property called Disposed, which indicates that the object has been disposed.
Add a protected Dispose(bool) method. The public Dispose() method has no parameters.
When Dispose() is called, if the Disposed property is false, it will call Dispose(true), and call GC.SuppressFinalize() to disable the finalizer. Ths is essential to keep .NET's garbage collector happy. Classes with unspressed finalizers go to the end of the line for garbage collector cleanup, so they become almost a memory leak.
The public Dispose() method should then set the Disposed property to true.
The finalizer calls Dispose(false).
The Dispose(bool) will always clean up its own managed resources, but it will clean up unmanaged resources only when called as Dispose(true). Note that all resource cleanup is in the protected Dispose(bool) method, not in the public Dispose() method.
If the class is not sealed, then the protected Dispose(bool) method should be a virtual method. Subclasses that need to do cleanup can override Dispose(bool) and followht e same logic as above. In addition, they should call base.Dispose(bool) with the parameter they were given.
If .net, if you can use an object in a "using" statement, that means the object implements iDisposable and you should when practical call it's disposal method when you're done with it. Note that the disposal method may not always be called "Dispose", but you can always call it by casting the object to iDisposable and then calling Dispose on that.
Note that some types of "iDisposable" objects don't handle any unmanaged resources, but do subscribe to events. If such an object isn't properly disposed, it might not get garbage-collected unless or until all of the objects for which it holds subscribed events are themselves garbage-collected. In some cases, that may never happen until an application exits.
For example, the enumerator returned by an iEnumerable collection might subscribe to that object's "collection changed" event, unsubscribing when its dispose method is called. If the dispose method is never called, the enumerator would remain around as long as the collection did. If the collection itself stayed around a long time and was enumerated frequently, this could create a huge memory leak.
I'm in agreement with the above, I'll just add to the subsequent question about setting a variable to null.
You don't need to do this with variables used in a method (they will fall out of scope so it's only if they have state within them that must be signalled as needing clean-up, through IDisposable.Disopse that you have to worry abou this).
It's rarely useful for instance or static members, as memory isn't as precious a resource as people often think (it is a precious resource, but most attempts to deal with it in a few lines of code is like turning off your taps while you've a burst main.
It is though useful if you have a static or instance member of a class and (A) it is a large object (B) the "owning" object is likely to stay in memory for a long time and (C) you know you won't need that value gain, to set that member to null.
In practice this isn't a very common combination. If in doubt, just leave alone.
Now, do read the other answers here, as what they say about the Dispose() method is much more important.

Do I have to release all the native resource before a GC happens?

We know that .NET has 2 super types. The Value-Type and Reference-Type. As I understand it, after I set all the roots of an Ref-Type object to null, the Ref-Type object is logically deleted from the stack, but remains in existence on the manged-heap. If the Ref-Type object uses some native resources, such as an opened-file, do I have to release these resources before or after I setting all the roots to null? And why?
If a reference type has native resources, whether directly or indirectly, it should implement IDisposable. You should call Dispose when you've finished using the object (assuming you "own" the resource), preferably with a using statement:
using (Foo foo = new Foo(...))
{
...
} // Dispose called here
The Dispose method should release all the resources.
If the type has direct references to unmanaged resources - usually via an IntPtr - then it should have a finalizer. However, .NET 2.0 made this a lot simpler with SafeHandle which can be used instead of IntPtr. The advent of SafeHandle basically means that very very few types should have a finalizer these days.
There are a few things that need to be clarified in your assumptions in order to give you an answer.
For most intents and purposes, .NET only has one "super" type, and that is System.Object.
(For the record there are some types in the type system that do not derive from System.Object)
System.ValueType inherits from System.Object.
Once you release all of the references to an object, then the object becomes eligible for garbage collection. It does not get deleted when the last reference is released. At some indeterminate point in the future, the memory that the object was stored in on the managed heap will be reclaimed by a garbage collection.
If the instance does in fact use some sort of native resources, then it should implement the IDisposable interface.
If this interface is implemented on the class your object is an instance of, then you should call the Dispose method, as a "proper" implementation of IDisposable would release any unmanaged resources (such as file handles, as you mention) at the time that Dispose is called.
If the Dispose method is not called on a class instance that implements IDisposable, and it is a "proper" implementation of that interface, then when the object is finalized, the unmanaged resources will be cleaned up.
However, just because a "proper" implementation of IDisposable will guarantee that unmanaged resources will be disposed of at some point in the future, it doesn't mean that one should not call Dispose. The presence of the IDisposable interface indicates that you should call Dispose as-soon-as-possible.
If you allocate native resources yourself (not via other means of the .NET-Framework), you have to release them before you are garbage-collected. This can/should be done by using a "Finalizer", i.e. ~MyClass() which must NOT be confused with a destructor in C++.
Finalizers make GC slow, because they are executed on a separate thread and therefore require two GC cylces to get rid of an object.
Therefore you should also implement IDisposable where you free your native resources and call GC.SuppressFinalize(this).
You should not release the unmanaged resources directly unless you create you own unmanaged resource wrapper. Usually you call Dispose or Close to free the unmanaged resource. This is done to provide some control on how resources are reclaimed. If you use some class that wraps an unmanaged resource and provide some finalizer the Garbage Collector will reclaim the resource when the Finalizer Queue thread is handling the object. See Jeffrey Richter's article for more information
If you have an object that is using native resources, then you must make sure that object implements IDisposable interface. You can then call MyObject.Dispose() and in that Dispose() method, make sure you're cleaning up your native resources.
Simply setting the object to NULL is not enough since the native resource will hang around in memory.

Categories