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

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.

Related

Dispose(true) never called on Xamarin.Android 'Java.Object' [duplicate]

I am confused about dispose. I am trying to get my code disposing resources correctly. So I have been setting up my classes as IDisposable (with a Dispose method) them making sure that the Dispose method gets called.
But now FXCop is telling me lots of stuff about disposing = false and calling Dispose(false).
I don't see a Dispose method that takes a bool. Do I need to make one? If so, why? Why not just have a method that gets called when it is disposing?
I saw some code here: CA1063: Implement IDisposable correctly - Microsoft Docs that shows how to make a Dispose method that takes a bool. It says it is for native vs managed resourses. But I thought the whole point of dispose was for unmanaged resourses only.
Also, the line that FXCop is complaining about is this:
~OwnerDrawnPanel()
{
_font.Dispose();
}
It says:
CA1063 : Microsoft.Design : Modify 'OwnerDrawnPanel.~OwnerDrawnPanel()' so that it calls Dispose(false) and then returns.
But Font does not have a Dispose(bool) on it (that I can find).
To sum it up:
Why do I need a Dispose(bool)? and if I do, why doesn't Font have it? and since it does not have it, why is FXCop asking me to use it?
Thanks for all the great answers. I think I understand now. Here is
The answer as I see it:
Disposing of "unmanaged" resources falls into two categories:
Resources that are wrapped in a managed class (ie Bitmap, Font etc), but still need Dispose to be called to clean them up properly.
Resources that you have allocated, which are representations of native resources (ie device contexts that need to be released)
Dispose(bool) is used to tell the difference between the two:
When Dispose is directly called on your object, you want to free both kinds of "unmanaged" resources.
When your object is up for Garbage Collection, you don't need to worry about the first kind of resources. The garbage collector will take care of them when it cleans them up. You only need to worry about true native resources that you have allocated (if any).
Dispose(bool) is a pattern to implement Finalize and Dispose to Clean Up Unmanaged Resources , see this for detail
IDisposable provides a method with the signature
public void Dispose()
Microsoft best practices (Implement a Dispose method) recommend making a second private method with the signature
private void Dispose(bool)
Your public Dispose method and finalizer should call this private Dispose method to prevent disposing managed resources multiple times.
You can fix the warning you are getting by either implementing IDisposable and disposing of your font object in the dispose method, or creating a Dispose(bool) method in your class, and make your finalizer call that method.
Dispose(bool) is not meant to be public and that is why you don't see it on Font.
In case some user of your class forgets to call Dispose on your method, you will release the unmanaged resources only by making a call to Dispose(false) in the Finalizer.
In case IDispose is called correctly, you call the Dispose on managed resources and also take care of the unmanaged.
The flag is to distinguish the two cases.
It is a pattern recommended by MSDN.
FxCop says you should implement the Disposable pattern like described here. Note that you should not use finalizers for disposing managed resources like _font is. Finalizers are used for cleaning up unmanaged resources. If you do not execute the cleanup logic in the Dispose method of your (sub)class they are executed non-deterministically by the garbage collector.
Also please note that it is very rarely that you need to do anything in the destructor. Regularly, everything is taken care of by the garbage collector. For example, in your code, you don't need to dispose the _font object in the OwnerDrawnPanel's destructor. Since the panel is getting cleaned up by the GC, so will be _font, because panel was the only one who referenced it, right?
Generally, if you own disposable objects, you only need to dispose them when your own Dispose method was called. But NOT in the destructor. When your destructor is running, you can bet that all your aggregated objects are being cleaned up as well.
You should almost never need to use finalizers. They are only for classes that directly contain unmanaged resources, and in .NET 2.0+ those should be wrapped in SafeHandle.
I think Dispose(true) will free both the managed and unmanaged resource as we need to not call finalize again that's why we write GC.SupressFinalize() after Dispose(true).
We call Dispose(false) in destructors to free unmanaged resources and will be called by Runtime and not user's code.
Agreeing with Kumar, the Dispose(bool disposing) pattern is also documented on MSDN. The distinction is not between managed and unmanaged resources, but whether Dispose is being called by your code or the runtime.
I found a good article about correct implementation of IDispose interface: http://msdn.microsoft.com/en-us/library/ms244737(v=vs.80).aspx
The pattern of implementing a public public void Dispose(), protected virtual void Dispose(bool), and ~ClassName() finalizers is a best practice recommended by Microsoft as a way to neatly organize your cleanup code for both managed and unmanaged resources.
Basically, the code that uses your Disposable class should call Dispose(), but if it doesn't, the finalizer ~ClassName() will get called by Garbage Collection, and based on which one of those is used, you set the argument to Dispose(bool) as true or false, and in your Dispose(bool), you only clean up managed resources if the argument is true.
The warning you are getting seems to specifically recommend that you use this practice in your finalize method ~ClassName().

More information on how C# Dispose works

In trying to understand the IDisposable i have a few questions that most answers haven't explicitly stated.
If we call dispose on an object, does that dispose the object at that time or just class members that we would like to clean up, and the whole object would be destroyed later by the GC.
After we suppress the finalizer in the dispose method, will the GC still clean up all the class members we didn't clean up in the dispose?
An object will be garbage collected once all references to it are gone, in a non-deterministic way. Garbage collection
from MSDN : Garabge collection fundamentals
Garbage collection occurs when one of the following conditions is
true:
The system has low physical memory.
The memory that is used by allocated objects on the managed heap
surpasses an acceptable threshold. This means that a threshold of
acceptable memory usage has been exceeded on the managed heap. This
threshold is continuously adjusted as the process runs.
The GC.Collect method is called. In almost all cases, you do not have
to call this method, because the garbage collector runs continuously.
This method is primarily used for unique situations and testing.
Garabge collection when to use
Understanding Object life cycle
First things first, there is a ton of duplicate questions here on this topic. If truly none other answer explicitly answers your question, here they are, but I expect this to be closed as a duplicate.
First, Dispose is just a method, an ordinary method. It does not deal with Garbage Collection at all.
So what does Dispose do? It should be used to clean up unmanaged resources, such as file handles, window handles, etc. Things that the .NET garbage collector does not know about.
So to answer question 1: "Yes", when you call Dispose on an object, it is disposed there and then. There is no mark set on the class to indicate cleanup later on.
Since Dispose does not deal with Garbage Collection, you can easily keep a reference to the object after disposing it, and it will not be garbage collected. Garbage collection only occurs when there are no more references to the object. This can happen even if you have not called Dispose on the object, but it will not happen because you call Dispose on the object.
Second question: When GC collects the object after it has been through the finalizer cycle, then GC will clean up the object + any object it refers to that no longer has any references left (besided the one from your object). This happens at some point, and not necessarily all at once either.
Suppressing the finalizer is just making sure GC does not do more work than necessary, by saying that "when you find this object and determine that it is eligible for collection, then just go ahead and collect it, I have taken care of the 'finalization' cleanup so you don't have to".
Firstly and most important you need to understand that disposing an object and garbage collecting an object are completely different things - make sure that you don't confuse the two!
If we call dispose on an object the only thing that happens is that the Dispose method gets called. It might be that the Dispose method then goes on to call GC.SuppressFinalize, but then again it might not do anything at all - its completely up to the implementation.
When we call GC.SuppressFinalize the only thing that happens is that it requests that the GC not call the objects finalizer when the object is collected (almost as if the object didn't have a finalizer in the first place).
As it happens a common pattern is for objects which have a finalizer to also implement IDisposable so that unmanaged resources can be cleaned up deterministicly - if this happens then there is no need for the GC to call the finalizer as the work that would have been done in the finalizer has already been performed when we called Dispose - calling GC.SuppressFinalize is just a friendly hint to the GC that it doesn't really need to call the finalizer after all.
1) When you call dispose on an object, all that happens is that the code in its Dispose() method is run. This code may of course call Dispose() for one or more of its fields, but it's not required to.
It may also call the base class' Dispose(true), if any (via base.Dispose()), but that is using the Dispose Idiom; Dispose(bool) is NOT part of the IDisposable interface.
2) The finalizer is suppressed only for the specific object for which SuppressFinalize() was called. It won't affect any other objects (including any held by fields of the object for which SuppressFinalize() was called).

Difference between destructor, dispose and finalize method

I am studying how garbage collector works in c#. I am confused over the use of Destructor, Dispose and Finalize methods.
As per my research and understandings, having a Destructor method within my class will tell the garbage collector to perform the garbage collection in the way mentioned in the destructor method which cannot be called explicitly on the instances of the class.
The Dispose method is meant to provide the user to control the garbage collection. The Finalize method frees the resources used by the class, but not the object itself.
I am not sure if I understand it the right way. Please clarify the doubts. Any further links or guides are welcome.
Destructor implicitly calls the Finalize method, they are technically the same. Dispose is available with objects that implement the IDisposable interface.
You may see : Destructors C# - MSDN
The destructor implicitly calls Finalize on the base class of the
object.
Example from the same link:
class Car
{
~Car() // destructor
{
// cleanup statements...
}
}
The Destructor's code is implicitly translated to the following code:
protected override void Finalize()
{
try
{
// Cleanup statements...
}
finally
{
base.Finalize();
}
}
Your understanding for the Destructor is right:
From MSDN
The programmer has no control over when the destructor is called
because this is determined by the garbage collector. The garbage
collector checks for objects that are no longer being used by the
application. If it considers an object eligible for destruction, it
calls the destructor (if any) and reclaims the memory used to store
the object. Destructors are also called when the program exits. It is
possible to force garbage collection by calling Collect, but most of
the time, this should be avoided because it may create performance
issues.
In C# terms, a destructor and finalizer are basically interchangeable concepts, and should be used to release unmanaged resources when a type is collected, for example external handles. It is very rare that you need to write a finalizer.
The problem with that is that GC is non-deterministic, so the Dispose() method (via IDisposable) makes it possible to support deterministic cleanup. This is unrelated to garbage collection, and allows the caller to release any resources sooner. It is also suitable for use with managed resources (in addition to unmanaged), for example if you have a type that encapsulates (say) a database connection, you might want disposing of the type to release the connection too.

Do I need to call Dispose() on a static object?

If I have a static WebClient object, do I need to call Dispose() on it at the end of Main()?
You should always Dispose() objects when you're finished with them, regardless of where you put the object.
If the object is in a static field, it may be more difficult to figure out when you're finished with it.
As a general rule, you should dispose of any disposable objects. This will allow them to clean up any resources. However, there is no guarantee that dispose will be called on a disposable type - the consumer could neglect to call it, and the CLR does not automatically call it.
If a type really needs its clean-up logic to execute (such as when allocating unmanaged memory or creating a heap of files on the file system), it should implement a finalizer in conjunction with the dispose pattern. The CLR will call the finalizer on process exit if it hasn't already been called (typically through disposing the object). Yes, there are some caveats around this (a bad finalizer can spoil the party for other finalizable instances, for example) but the CLR guarantees to at least try to run all finalizers on process exit.
So technically, I don't there's any reason why you absolutely must call the dispose method in this case. However, it's a good habit to get into nevertheless.

IDisposable with destructor: requires thread-safe implementation?

This is pretty much only for me to make sure, I got this right:
We have a large resource class implementing the IDisposal pattern. It should (by design) be implemented in a way, that enables it to get called more than one time (even if we try to call it exactly one time of course). We also implement a finalizer, which also calls the Dispose() method - just as backup. If called manually, Dispose() will also call GC.SuppressFinalize(this).
There are several examples of disposal patterns around. Most of them call GC.SuppressFinalize(this) at the end of the disposing code. Some claim, it would be better, to call it at the beginning of the Dispose() method, before any cleaning. Latter argue, this would make sure, the GC doesn't call the finalizer concurrently, while we are still cleaning up.
Question:
It seems, placing GC.SuppressFinalize at the beginning doesn't do any better? We still have a race condition, right? So is it true, that we rather should implement Dispose() in a thread safe way instead?
The GC only cleans up objects that are not 'reachable'.
A class in which code is executing is still 'reachable' because it's this pointer is on the stack. So while dispose is executing, the finalizer won't be called.
So it does not matter if you call SuppressFinalize at the begin or end.
As commentors below indicated, the CLR implementation does not appear to guarantee that your object does not get garbage collected/finalized while instance methods are executing. The only possible 'dependable' reference keeping the object alive is the one used to invoke the method on the object, but I don't know enough about the JIT internals to make statements about that, and it's behaviour might change.
I'm leaving the answer here for access to the discussion below.
While it is sometimes possible for an object to be finalized while a seemingly-live reference exists, that can only happen when nothing else is going to ever refer to the object. The GC.SuppressFinalize(this) actively refers to the present object 'this', thus guaranteeing that it will not be finalized until the GC.SuppressFinalize executes. Further, the fact that the object reference existed to dispose the object, and was available to the Dispose method, guarantees that the finalizer couldn't have been queued before Dispose started running unless the object was dead and a finalizer somewhere (either its own finalizer, or that of some other object) resurrected it.
Because there are some scenarios where an object could be scheduled for finalization and resurrected without ever being aware of it, it may not be a bad idea to protect a dispose and finalize against redundant operation. Microsoft's pattern is not a good one, however. Finalizable objects shouldn't hold references to any objects not needed for finalization. If an object would hold a mixture of managed and unmanaged resources, the unmanaged resources should be moved into their own classes (effectively turning them into managed resources), so then the main object would hold nothing but managed resources.
Dispose should not throw any exceptions.
I would make sure all the code in Dispose is thread safe so that if it gets called it will not do anything strange. Usually adding checks if variables are null already should do the trick.
In the microsoft examples i've only seen GC.SuppressFinalize at the end of the Dispose function.

Categories