using in defining object in c# - c#

when we use using for defining an object?for example:
using (Login objLogin = new Login())
i know that we use when we want to clean the memory after using this object but i dont know when should we clean the memory.

The using statement should be used to timely dispose of objects which implement IDisposable. This does not actually clean managed memory but allows a managed object to release any unmanaged resources it may be holding and in some occasions remove references to managed objects to prevent memory leaks.
I suggest reading up on the following sites which provide in depth explanations of both IDisposable and the using statement
IDisposable, Finalizers and the definition of an unmanaged resource
http://www.codeproject.com/KB/dotnet/IDisposable.aspx

Whenever an object is disposable (it implements IDisposable interface) it means that it probably uses some unmanaged resources that can not be managed by garbage collector and therefore if your object is collected these resources might remain in the memory causing some problems. The solution for this problem is :
1.To implement IDisposable interface in such kind of objects and to clear/close unmanaged resources in Dispose method (for example if you are using a disposable object inside your object it'd be better to have a Dispose method to call its dispose inside)
2.To call the Dispose method of disposable objects when they are not needed anymore but be careful cause reusing a disposed object can throw some exceptions.
The using syntax that you mentioned is a short way of doing the same and it interprets this:
using(var obj=new myDisposableObject)
{
obj.Something();
}
into following :
var obj=new myDisposableObject();
try
{
obj.Something();
}
catch
{
throw;
}
finally
{
obj.Dispose();
}
thus you can always be sure that whatever happens the Dispose method of your object is always called.

You don't clean the memory; the object implementing IDisposable will clean its unmanaged resources in its Dispose method (or at least, that's the implication that the class is making by implementing IDisposable), and .NET will clean the memory when the object is collected.

Related

Advantage of using IDisposable over performing actions in C# class finalizer

There are a lot of question discussing the "patterned" was of implementing and using IDisposable/Dispose, but what advantage does it have over having all the cleanup code in C# class finilizer?
Sure other classes can explicitly call Dispose earlier than the class instance is garbage collected and the finilizer is called. Is it the only one?
You have no guarantees about when or even if a Finalizer (destructor) will be called.
So in order to timely cleanup resources (Files, Db Connections) the Dispose pattern is essential.
The IDisposable is made to avoid destructors. The problem with destructors is that you never know when they are called, and objects with destructors are always the last to be cleaned up.
Using IDisposable you inform the user of you class that they should be using thwe using-method.
Eg:
using(MyClass myClass = new MyClass())
{
// Do something with MyClass.
}

Will object with reference kept be disposed?

May I know if the "objectToBeDisposed" will be disposed if its reference are kept by the "useDisposableObject"?
using(IDisposable objectToBeDisposed = new ObjectImplementedIDisposable ()){
ChildObject useDisposableObject = new ChildObject(objectToBeDisposed);
.... doing stuff with useDisposableObject;
}
Yes, in your example it will be disposed, because the using block explicitly calls the Dispose() method when leaving that block.
As an aside the referencing object is within the using block scope and will go out of scope at the end of the using block, which will avoid the potential issue of accessing a disposed object if the referencing object tried to use it once it was disposed.
Update thanks to #dlev
Disposal, finalization and memory deallocation are 3 totally different things in the .NET world.
Disposal is only an "application logic" thing, it is implemented through the disposable pattern.
If you implement the interface IDisposable, your object can be used with the using keyword.
The using keyword will translate in a simple way:
using (IDisposable xxx = new MyObject())
{
....
}
means
{
IDisposable xxx = new MyObject();
try
{
....
}
finally
{
if (xxx != null)
xxx.Dispose();
}
}
There is no other magic in this. That's all.
Object finalization is instead called by garbage collector when the objects should be freed.
The time when it happens and the order between destructors is unpredictable.
class myclass { ~myclass() { this code will be called by garbage collector, i cannot call it } }
The syntax is very similar to C++ destructors but the meaning is a lot different.
And then memory deallocation.
Memory deallocation is not connected to object disposal!
You can keep forever a reference to a disposed object. Disposal is just something related to application logic.
Destructors can also be cancelled or called more than once by garbage collector (see GC.ReRegisterForFinalize and GC.SuppressFinalize).
The presence of a destructor in a class slow down a lot the garbage collector, and inside destructor, you can do almost nothing except releasing unmanaged resources.
Disposal instead as I said is an application thing, is just a method, and is not related to garbage collector.
"Disposing" an object has nothing to do with which references are kept around. IDisposable itself is just an interface, nothing more.
When a class implements that interface, a user of the class can call a public void Dispose() method on the object. When the user of the class places an instance of the class in a using block, the Dispose() method will automatically get called. When an Enumerator class implements IDisposable and is used in a foreach loop, it will also have Dispose() called on it.
This has absolutely nothing to do with which references are kept around, or the automatic garbage collection system.
However, IDisposable also has a design "contract" that goes with it. This contract is a pattern that classes that implement IDisposable must follow to have correct program behavior.
The contract is that once you've called Dispose(), you should never call any property or method on the object again, otherwise you should expect an ObjectDisposedException to be thrown. The only thing that is allowed to be called on that object after that point is Dispose() again, or the object finalizer (via garbage collection).
Because of this, people will sometimes set an reference to an IDisposable class to null after they have disposed it, so they don't accidentally call methods on the already-disposed object. If you placed the reference in a using block, you don't have to worry about this; The compiler won't even let you touch the reference again. If you try, you will get an error and your program will fail to compile.
This contract is not built into the language or CLR itself - it must manually be adhered to by the implementer of a class.
Yes, it will be. I might be wrong, but I don't think #John Weldon's explanation is not accurate though. You can only call using on an IDisposable implementing class, and when the using exits, it will call Dispose() on the object.
The part where I don't agree is the 'because the referencing object is within the using block scope and will go out of scope at the end of the using block' part. The objects declared in scope will not always be disposed of when the using exits. If you take this example
JustAClass myInstance = new JustAClass();
using ( MyDisposableClass theUsingInstance = new MyDisposableClass() )
{
AnotherClass innerInstance = new AnotherClass();
myInstance.ItsOtherClass = innerInstance;
myInstance.ItsWhatever = theUsingInstance;
}
At the end of this code, myInstance.ItsOtherClass is not null. innerInstance has been created in the using section and won't be garbage collected since there is still a referenced. However, the object refered by myInstance.ItsWhatever has been disposed of, since it's the using target.

What is the difference between Dispose and setting reference to null in C#?

I have two code samples and I want to know what is the deifference between them and which is better to use as best practice and performance wise:
using (TestForm test = new TestForm())
{
test.ShowDialog();
}
and the other is:
TestForm test = null;
try
{
test = new TestForm();
test.ShowDialog();
}
catch(Exception ex)
{
}
finally
{
test = null;
}
The IDisposable interface defines the Dispose method, as well as the possibility to use the "using" syntax. The dispose method of a class can be implemented to release resources, close database connections and any sort of finalizing and cleanup. Just setting the class instance to null won't execute any of the code defined in the dispose method. As a generic rule, if a class implements IDisposable, dispose should be called when you're finished with the class instance.
Dispose() is for freeing unmanaged resources. This may be done in a finalizer as well (which might call Dispose()) but don't rely on it. If it isn't done, then you leak unmanaged resources.
Setting a reference to null only means that a particular reference no longer points to that object. It can live on quite a while after that (or even indefinitely if you have another reference – well, if you have multiple reference to an object you Dispose()d of, then it gets ugly, probably).
Generally, always call Dispose() on IDiposables when you're done with them. It's easier if you wrap them into a using statement:
using (var foo = new SomeDiposableObject()) {
// do something with foo
}
The IDisposable pattern is a mechanism to timely free unmanaged and managed resources that an object may be consuming.
The typical way the pattern is implemented is as follows:
public void Dispose() //Implementes the IDisposable interface
{
this.Dispose(true);
GC.SupressFinalize(this); //All resources have been released, no need to run the finalizer. We make the GC's life a little easier;
}
protected void Dispose(bool disposing)
{
if (disposing)
{
//Relesase managed resources.
}
//Release unmanaged resources.
}
~MyDisposableObject() //finalizer
{
this.Dispose(false)
}
The thing to note here is that the release of resources through the Dispose method is very similar to what you logically would expect to find in a finalizer. It is not done directly in the finalizer due to two main reasons:
the finalizer is not executed in a deterministic order. That is why we do not dispose managed resources from the finalizer (Dispose(false)), as some or all the managed resources held by the object might have been finalized before the object itself. This is not true with unmanaged resources as, by definition, they will never be finalized by the GC.
We do not know when the finalizer is run (it is up to the GC).
The basic idea is that an object implementing IDisposable is a sign for any consumer saying: "hey, I'm holding on to a certain amount of unmanaged and/or managed resources that will eventually be released when the GC decides I'm no longer useful, but if you need those resources back in a timely way, call Dispose() and I'll be happy to oblige.".
On the other hand, setting a reference variable to null is not freeing any resources at all. If the reference you have removed from the object was the only one to said object, then the object will eventually be collected by the GC and managed and unmanaged resources will be freed (when, is anyones guess).
If there were more live references still pointing to the object, then the object would live one and no resources whatsoever would be freed.

Do I need to implement a dispose or finalize in my objects?

For too long I let the garbage collector do its magic, removing all responsibilities from my self.
Sadly it never turned into an issue... So I never gave a second thought to the subject.
Now when I think about it I don't really understand what the "dispose" function really does and how and when it should be implemented.
The same question for finalize...
And a last question...
I have a class pictureManipulation : when I need to save/resize/change format ... I start a new instance of that class use its objects and... well let the garbage collection kill the instance
class student
{
public void displayStudentPic()
{
PictureManipulation pm = new PictureManipulation();
this.studentPic = pm.loadStudentImage(id);
}
}
Class Test
{
student a = new Student();
a.displayStudentPic();
// Now the function execution is ended... does the pm object is dead? Will the GC will kill it?
}
Regarding your class Student
Do I need a Dispose() ?
Assuming the Picture class is IDisposable: Yes. Because a Student object 'owns' the studentPic and that makes it responsible for cleaning it up. A minimal implementation:
class Student : IDisposable
{
private PictureClass studentPic;
public void Dispose()
{
if (studentPic != null)
studentPic.Dispose();
}
...
}
And you now use a Student object like:
void Test
{
using (Student a = new Student())
{
a.displayStudentPic();
} // auto Dispose by using()
}
If you can't/don't use a using(){} block, simply call a.Dispose(); when you're done with it.
But please note that the (far) better design here would be to avoid keeping a picture object inside your Student object. That sets off a whole chain of responsibilities.
Do I need a Finalizer?
No. Because when a Student object is being collected, its studentPic object is guaranteed to be collected in the same run. A Finalizer (destructor) would be pointless but still expensive.
You only need to implement the Dispose method if your type holds some unmanaged resources like DB connections, file handles, etc. or if some of the objects that are held by your type implement the IDisposable interface. Here is a few points you should consider when implementing the standard Dispose pattern:
if your object doesn’t hold any IDisposable objects or unmanaged resources (DB connection, for example) then you don’t need to implement the IDisposable or finalizer at all
if your object holds references to IDisposable objects, then call Dispose() on these objects in the Dispose method
if your object doesn’t hold any unmanaged resources then don’t implement a finalizer, the Garbage Collector won’t attempt to finalize your object (which has a performance hit) unless you have implemented a finalizer.
if your object holds unmanaged resources, clean them up in the finalizer without re-writing any of the cleanup code in the Dispose(bool) method already.
You need to take care about object disposal if it holds resources other than just memory held by the object itself.
For instance, if your object abstracts a file, you must be in control when the file is released, or, you will mess things up very bad: your app finished using it and it will still be locked, until GC disposes your object.
To know how to do it properly, read manuals about dispose and finalize as well as the using(){} clause.

Finalize vs Dispose

Why do some people use the Finalize method over the Dispose method?
In what situations would you use the Finalize method over the Dispose method and vice versa?
The finalizer method is called when your object is garbage collected and you have no guarantee when this will happen (you can force it, but it will hurt performance).
The Dispose method on the other hand is meant to be called by the code that created your class so that you can clean up and release any resources you have acquired (unmanaged data, database connections, file handles, etc) the moment the code is done with your object.
The standard practice is to implement IDisposable and Dispose so that you can use your object in a using statment. Such as using(var foo = new MyObject()) { }. And in your finalizer, you call Dispose, just in case the calling code forgot to dispose of you.
Others have already covered the difference between Dispose and Finalize (btw the Finalize method is still called a destructor in the language specification), so I'll just add a little about the scenarios where the Finalize method comes in handy.
Some types encapsulate disposable resources in a manner where it is easy to use and dispose of them in a single action. The general usage is often like this: open, read or write, close (Dispose). It fits very well with the using construct.
Others are a bit more difficult. WaitEventHandles for instances are not used like this as they are used to signal from one thread to another. The question then becomes who should call Dispose on these? As a safeguard types like these implement a Finalize method, which makes sure resources are disposed when the instance is no longer referenced by the application.
Finalize is the backstop method, called by the garbage collector when it reclaims an object. Dispose is the "deterministic cleanup" method, called by applications to release valuable native resources (window handles, database connections, etc.) when they are no longer needed, rather than leaving them held indefinitely until the GC gets round to the object.
As the user of an object, you always use Dispose. Finalize is for the GC.
As the implementer of a class, if you hold managed resources that ought to be disposed, you implement Dispose. If you hold native resources, you implement both Dispose and Finalize, and both call a common method that releases the native resources. These idioms are typically combined through a private Dispose(bool disposing) method, which Dispose calls with true, and Finalize calls with false. This method always frees native resources, then checks the disposing parameter, and if it is true it disposes managed resources and calls GC.SuppressFinalize.
Finalize gets called by the GC when this object is no longer in use.
Dispose is just a normal method which the user of this class can call to release any resources.
If user forgot to call Dispose and if the class have Finalize implemented then GC will make sure it gets called.
Finalize
Finalizers should always be protected, not public or private so that the method cannot be called from the application's code directly and at the same time, it can make a call to the base.Finalize method
Finalizers should release unmanaged resources only.
The framework does not guarantee that a finalizer will execute at all on any given instance.
Never allocate memory in finalizers or call virtual methods from finalizers.
Avoid synchronization and raising unhandled exceptions in the finalizers.
The execution order of finalizers is non-deterministic—in other words, you can't rely on another object still being available within your finalizer.
Do not define finalizers on value types.
Don't create empty destructors. In other words, you should never explicitly define a destructor unless your class needs to clean up unmanaged resources and if you do define one, it should do some work. If, later, you no longer need to clean up unmanaged resources in the destructor, remove it altogether.
Dispose
Implement IDisposable on every type that has a finalizer
Ensure that an object is made unusable after making a call to the Dispose method. In other words, avoid using an object after the Dispose method has been called on it.
Call Dispose on all IDisposable types once you are done with them
Allow Dispose to be called multiple times without raising errors.
Suppress later calls to the finalizer from within the Dispose method using the GC.SuppressFinalize method
Avoid creating disposable value types
Avoid throwing exceptions from within Dispose methods
Dispose/Finalized Pattern
Microsoft recommends that you implement both Dispose and Finalize when working with unmanaged resources. The Finalize implementation would run and the resources would still be released when the object is garbage collected even if a developer neglected to call the Dispose method explicitly.
Cleanup the unmanaged resources in the Finalize method as well as Dispose method. Additionally call the Dispose method for any .NET objects that you have as components inside that class(having unmanaged resources as their member) from the Dispose method.
There're some keys about from the book MCSD Certification Toolkit (exam 70-483) pag 193:
destructor ≈(it's almost equal to) base.Finalize(), The destructor is converted into an override version of the Finalize method that executes the destructor’s code and then calls the base class’s Finalize method. Then its totally non deterministic you can't able to know when will be called because depends on GC.
If a class contains no managed resources and no unmanaged resources, it shouldn't implement IDisposable or have a destructor.
If the class has only managed resources, it should implement IDisposable but it shouldn't have a destructor. (When the destructor executes, you can’t be sure managed objects still
exist, so you can’t call their Dispose() methods anyway.)
If the class has only unmanaged resources, it needs to implement IDisposable and needs a destructor in case the program doesn’t call Dispose().
Dispose() method must be safe to run more than once. You can achieve that by using a variable to keep track of whether it has been run before.
Dispose() should free both managed and unmanaged resources.
The destructor should free only unmanaged resources. When the destructor executes, you
can’t be sure managed objects still exist, so you can’t call their Dispose methods anyway. This is obtained by using the canonical protected void Dispose(bool disposing) pattern, where only managed resources are freed (disposed) when disposing == true.
After freeing resources, Dispose() should call GC.SuppressFinalize, so the object can
skip the finalization queue.
An Example of a an implementation for a class with unmanaged and managed resources:
using System;
class DisposableClass : IDisposable
{
// A name to keep track of the object.
public string Name = "";
// Free managed and unmanaged resources.
public void Dispose()
{
FreeResources(true);
// We don't need the destructor because
// our resources are already freed.
GC.SuppressFinalize(this);
}
// Destructor to clean up unmanaged resources
// but not managed resources.
~DisposableClass()
{
FreeResources(false);
}
// Keep track if whether resources are already freed.
private bool ResourcesAreFreed = false;
// Free resources.
private void FreeResources(bool freeManagedResources)
{
Console.WriteLine(Name + ": FreeResources");
if (!ResourcesAreFreed)
{
// Dispose of managed resources if appropriate.
if (freeManagedResources)
{
// Dispose of managed resources here.
Console.WriteLine(Name + ": Dispose of managed resources");
}
// Dispose of unmanaged resources here.
Console.WriteLine(Name + ": Dispose of unmanaged resources");
// Remember that we have disposed of resources.
ResourcesAreFreed = true;
}
}
}
99% of the time, you should not have to worry about either. :) But, if your objects hold references to non-managed resources (window handles, file handles, for example), you need to provide a way for your managed object to release those resources. Finalize gives implicit control over releasing resources. It is called by the garbage collector. Dispose is a way to give explicit control over a release of resources and can be called directly.
There is much much more to learn about the subject of Garbage Collection, but that's a start.
The finalizer is for implicit cleanup - you should use this whenever a class manages resources that absolutely must be cleaned up as otherwise you would leak handles / memory etc...
Correctly implementing a finalizer is notoriously difficult and should be avoided wherever possible - the SafeHandle class (avaialble in .Net v2.0 and above) now means that you very rarely (if ever) need to implement a finalizer any more.
The IDisposable interface is for explicit cleanup and is much more commonly used - you should use this to allow users to explicitly release or cleanup resources whenever they have finished using an object.
Note that if you have a finalizer then you should also implement the IDisposable interface to allow users to explicitly release those resources sooner than they would be if the object was garbage collected.
See DG Update: Dispose, Finalization, and Resource Management for what I consider to be the best and most complete set of recommendations on finalizers and IDisposable.
Diff between Finalize and Dispose methods in C#.
GC calls the finalize method to reclaim the unmanaged resources(such as file operarion, windows api, network connection, database connection) but time is not fixed when GC would call it. It is called implicitly by GC it means we do not have low level control on it.
Dispose Method: We have low level control on it as we call it from the code. we can reclaim the unmanaged resources whenever we feel it is not usable.We can achieve this by implementing IDisposal pattern.
The summary is -
You write a finalizer for your class if it has reference to unmanaged
resources and you want to make sure that those unmanaged resources
are released when an instance of that class is garbage collected
automatically. Note that you can't call the Finalizer of an object explicitly - it's called automatically by the garbage collector as and when it deems necessary.
On the other hand, you implement the IDisposable interface(and
consequently define the Dispose() method as a result for your class) when your class
has reference to unmanaged resources, but you don't want to wait for
the garbage collector to kick in (which can be anytime - not in
control of the programmer) and want to release those resources as
soon as you are done. Thus, you can explicitly release unmanaged resources by calling an object's Dispose() method.
Also, another difference is - in the Dispose() implementation, you should release managed resources as well, whereas that should not be done in the Finalizer. This is because it's very likely that the managed resources referenced by the object have already been cleaned up before it's ready to be finalized.
For a class that uses unmanaged resources, the best practice is to define both - the Dispose() method and the Finalizer - to be used as a fallback in case a developer forgets to explicitly dispose off the object. Both can use a shared method to clean up managed and unmanaged resources :-
class ClassWithDisposeAndFinalize : IDisposable
{
// Used to determine if Dispose() has already been called, so that the finalizer
// knows if it needs to clean up unmanaged resources.
private bool disposed = false;
public void Dispose()
{
// Call our shared helper method.
// Specifying "true" signifies that the object user triggered the cleanup.
CleanUp(true);
// Now suppress finalization to make sure that the Finalize method
// doesn't attempt to clean up unmanaged resources.
GC.SuppressFinalize(this);
}
private void CleanUp(bool disposing)
{
// Be sure we have not already been disposed!
if (!this.disposed)
{
// If disposing equals true i.e. if disposed explicitly, dispose all
// managed resources.
if (disposing)
{
// Dispose managed resources.
}
// Clean up unmanaged resources here.
}
disposed = true;
}
// the below is called the destructor or Finalizer
~ClassWithDisposeAndFinalize()
{
// Call our shared helper method.
// Specifying "false" signifies that the GC triggered the cleanup.
CleanUp(false);
}
The best example which i know.
public abstract class DisposableType: IDisposable
{
bool disposed = false;
~DisposableType()
{
if (!disposed)
{
disposed = true;
Dispose(false);
}
}
public void Dispose()
{
if (!disposed)
{
disposed = true;
Dispose(true);
GC.SuppressFinalize(this);
}
}
public void Close()
{
Dispose();
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// managed objects
}
// unmanaged objects and resources
}
}
The main difference between Dispose and Finalize is that:
Dispose is usually called by your code. The resources are freed instantly when you call it. People forget to call the method, so using() {} statement is invented. When your program finishes the execution of the code inside the {}, it will call Dispose method automatically.
Finalize is not called by your code. It is mean to be called by the Garbage Collector (GC). That means the resource might be freed anytime in future whenever GC decides to do so. When GC does its work, it will go through many Finalize methods. If you have heavy logic in this, it will make the process slow. It may cause performance issues for your program. So be careful about what you put in there.
I personally would write most of the destruction logic in Dispose. Hopefully, this clears up the confusion.
Class instances often encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize Method on an object (destructor syntax in C# and the Managed Extensions for C++). The garbage collector calls this method at some point after there are no longer any valid references to the object.
In some cases, you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. To provide explicit control, implement the Dispose method provided by the IDisposable Interface. The consumer of the object should call this method when it is done using the object. Dispose can be called even if other references to the object are alive.
Note that even when you provide explicit control by way of Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose.
I searched the answer to this question a lot today. I will share my learnings here. My answer is based on this link, because it has the clearest explanation I have seen.
When your objects has access to unmanaged resources, you have to manually release those resources. This can be done via IDisposable or finalizer meaning they both release unmanaged resources.
Rule of thumb:
Implement IDisposable to release unmanaged resources and caller code must call Dispose method. If caller forgets to call Dispose() method, you still can provide a method to release those unmanaged resources. First option is using safe handle to wrap unmanaged resource. Second option is defining a finalizer. Using safe handle is recommended way in this case.
I think this link is the clearest answer to this question. I do not know why people provide complex explanations to this question on the internet. It made me feel confused until I find that link.
As we know dispose and finalize both are used to free unmanaged resources..
but the difference is finalize uses two cycle to free the resources , where as dispose uses one cycle..
To answer on the first part you should provide examples where people use
different approach for the exact same class-object.
Otherwise it is difficult (or even strange) to answer.
As for the second question better read first this
Proper use of the IDisposable interface
which claims that
It's your choice! But choose Dispose.
In other words: The GC only knows about finalizer (if any. Also known as destructor to Microsoft).
A good code will attempt to cleanup from both (finalizer and Dispose).

Categories

Resources