Click to See Complete Forum and Search --> : dispossing object
popskie
May 31st, 2006, 03:07 AM
Hi,
What is the right time to call dispose,close(),set to null in every object.
It is effecient to call like this.
if ( OBJECT != null)
{
OBJECT .Close();
OBJECT .Dispose();
OBJECT =null;
}
and what object type need to be dispose?
Thanks ,
POpskie
jmcilhinney
May 31st, 2006, 03:19 AM
If you've finished using an object and it has a Dispose method then call it, unless it is one of the few types that are disposed by calling their Close method, like the Form class.
Close depends on the object. As I said, Form.Close Disposes the form, while Close for things like SqlConnections doesn't.
Setting variables to null is usually pointless. Do it only if you have finished with the object that the variable refers to and the variable will not or may not lose scope for some time, like a class-level variable or local variable in a long-running block.
Disposing an object and setting a variable to null achieve different things.
Calling the Dispose method of an object releases any resources that that object may be holding, and any resources that its members may be holding. This is basically to release OS-level, unmanaged resources no matter how deep they are buried within the object. If you don't do this then those resources are unavailable to the system until the garbage collector invokes the object's Finalize method, which could be some time.
Setting a variable to null removes the reference to the object that it referred to. Once an object has no more references it is available for garbage collection, so the actual memory space it is occupying can be reclaimed.
If you do not call Dispose on an object that supports it then it will take at least two passes by the garbage collector to clean it up, so there's more inefficiency.
In C#, and VB too now, It's a good idea to enclose a block where you intend to use an IDisposable object in a using block. This will implicitly Dispose the object, even if an exception is thrown within the block. An OpenFileDialog is a great example:using (OpenFileDialog ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() = DialogResult.OK)
{
// Open file here.
}
} // ofd.Dispose() is implicitly invoked here.
jmcilhinney
May 31st, 2006, 03:23 AM
Don't miss my edit above. :)
popskie
May 31st, 2006, 03:37 AM
thanks JM for the nice info.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.