472,362 Members | 1,927 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,362 software developers and data experts.

Call Dispose in a method?

Hi Everyone,

I've read most of the posts regarding "Dispose" in this NG.
I still have some questions.

If I declare and use a disposable object (say a DB connection) within
a method, is it worth calling Dispose() within my "finally" block,
even if that object only has local scope?

When the thread exits this method, won't the GC collect my disposable
object regardless of whether I call Dispose() or not?

What would be the difference between calling Dispose() here and not
calling Dispose()?

Thanks for clearing my confusion...
Wobbles
Nov 15 '05 #1
14 6553
wobbles <no***************************@nospam.hotmail.co m> wrote:
I've read most of the posts regarding "Dispose" in this NG.
I still have some questions.

If I declare and use a disposable object (say a DB connection) within
a method, is it worth calling Dispose() within my "finally" block,
even if that object only has local scope?
Absolutely - although I'd use a using() block.
When the thread exits this method, won't the GC collect my disposable
object regardless of whether I call Dispose() or not?
No. The GC doesn't run at the end of every method - it runs when it
feels it needs to.
What would be the difference between calling Dispose() here and not
calling Dispose()?


Timing - if you call Dispose(), all the appropriate cleaning up will be
done by the time the call returns, rather than at some indeterminate
point in the future.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
Disposable objects are objects that typicall use resources that the GC is
slow to reclaim or may not reclaim at all. By calling Dispose() you let
the object know that it should release it's resources. It will do so, and
wait to be eaten by GC.

If you don't call Dispose() you run the risk of running out of resources
(GC isn't very good at cleaning up those).

--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
For a laugh, try web browsing with Opera's User Mode and Nostalgia enabled
Nov 15 '05 #3
wobbles wrote:
If I declare and use a disposable object (say a DB connection) within
a method, is it worth calling Dispose() within my "finally" block,
even if that object only has local scope?
Yes. You should ALWAYS call Dispose if you do not need this object anymore.

When the thread exits this method, won't the GC collect my disposable
object regardless of whether I call Dispose() or not?


GC only calls finalizers, not Dipose()...

The object should implement a finilizer if this situation is allowed.
Some objects have the IDisposable-Interface but they are not implemeting a
Finalizer.

So if you do not call Dispose the resourse will never be freed (maybe at
program termination)
--
Greetings
Jochen

Do you need a memory-leak finder ?
http://www.codeproject.com/tools/leakfinder.asp
Nov 15 '05 #4
And the finallizer normally calls dispose (except not the unmanaged path if
you follow the normal pattern for IDisposable)
"Jochen Kalmbach" <no********************@holzma.de> wrote in message
news:Xn*********************************@127.0.0.1 ...
wobbles wrote:
If I declare and use a disposable object (say a DB connection) within
a method, is it worth calling Dispose() within my "finally" block,
even if that object only has local scope?
Yes. You should ALWAYS call Dispose if you do not need this object

anymore.
When the thread exits this method, won't the GC collect my disposable
object regardless of whether I call Dispose() or not?


GC only calls finalizers, not Dipose()...

The object should implement a finilizer if this situation is allowed.
Some objects have the IDisposable-Interface but they are not implemeting a
Finalizer.

So if you do not call Dispose the resourse will never be freed (maybe at
program termination)
--
Greetings
Jochen

Do you need a memory-leak finder ?
http://www.codeproject.com/tools/leakfinder.asp

Nov 15 '05 #5
<snip>
If I declare and use a disposable object (say a DB connection) within
a method, is it worth calling Dispose() within my "finally" block,
even if that object only has local scope?


Absolutely - although I'd use a using() block.


I understand that the "using()" block replaces "try" and "finally" but
how do I implement a catch to handle exceptions when I use "using"?
When the thread exits this method, won't the GC collect my disposable
object regardless of whether I call Dispose() or not?


No. The GC doesn't run at the end of every method - it runs when it
feels it needs to.


Ah, I wasn't sure about this. Thanks for clearing it up.
I thought that exiting the method would be a trigger for the GC.
Obviously not.
What would be the difference between calling Dispose() here and not
calling Dispose()?


Timing - if you call Dispose(), all the appropriate cleaning up will be
done by the time the call returns, rather than at some indeterminate
point in the future.


Thanks Jon.
Nov 15 '05 #6
Thanks for answering my questions. I've read all replies and they've all been
useful.

I have one more question:

I had thought of implementing the IDisposable interface in my class but there
are no class-level variables that need disposing. I only have declarations of
references to disposable objects within methods.

Should I implement IDisposable? *What* would I dispose when I override Dispose()
(considering my disposable object is in a method)?

Say I have:

public class Wobbles {

public Wobbles {}

public void DoThings() {
DisposableObject o = null;
try {
o = new DisposableObject();
o.Dosomething();
}catch (Exception e) {
//catch exceptions
}finally {
if (o!=null) o.Dispose();
}
}
}
Nov 15 '05 #7
wobbles <no***************************@nospam.hotmail.co m> wrote:
Absolutely - although I'd use a using() block.


I understand that the "using()" block replaces "try" and "finally" but
how do I implement a catch to handle exceptions when I use "using"?


I would personally either wrap the using block in a try/catch, or wrap
the try/catch in a using block. I'd prefer that to doing the finally
block explicitly, just for easy maintenance.

<snip>

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #8
wobbles,

If you need to catch exceptions, then in this case, do not use "using".
Use a try/catch/finally block and make sure you declare your variables
outside of the block and initialized to null (initialize in the block).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"wobbles" <no***************************@nospam.hotmail.co m> wrote in
message news:v9********************************@4ax.com...
<snip>
If I declare and use a disposable object (say a DB connection) within
a method, is it worth calling Dispose() within my "finally" block,
even if that object only has local scope?


Absolutely - although I'd use a using() block.


I understand that the "using()" block replaces "try" and "finally" but
how do I implement a catch to handle exceptions when I use "using"?
When the thread exits this method, won't the GC collect my disposable
object regardless of whether I call Dispose() or not?


No. The GC doesn't run at the end of every method - it runs when it
feels it needs to.


Ah, I wasn't sure about this. Thanks for clearing it up.
I thought that exiting the method would be a trigger for the GC.
Obviously not.
What would be the difference between calling Dispose() here and not
calling Dispose()?


Timing - if you call Dispose(), all the appropriate cleaning up will be
done by the time the call returns, rather than at some indeterminate
point in the future.


Thanks Jon.

Nov 15 '05 #9
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard.caspershouse.com> wrote:
If you need to catch exceptions, then in this case, do not use "using".
Use a try/catch/finally block and make sure you declare your variables
outside of the block and initialized to null (initialize in the block).


I don't like doing that as it "pollutes" the variable namespace. I'd
rather use:

try
{
using (...)
{
}
}
catch (...)
{
}

or

using (...)
{
try
{
}
catch (...)
}

personally. It's then easier to make sure you're cleaning things up,
'cos you only need to check that your using block is there.

Just personal preference though.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #10
wobbles <no***************************@nospam.hotmail.co m> wrote:
Thanks for answering my questions. I've read all replies and they've all been
useful.

I have one more question:

I had thought of implementing the IDisposable interface in my class but there
are no class-level variables that need disposing. I only have declarations of
references to disposable objects within methods.


In that case you don't need to implement it. You should only implement
it if you've really got something to do.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #11
<snip>
I had thought of implementing the IDisposable interface in my class but there
are no class-level variables that need disposing. I only have declarations of
references to disposable objects within methods.


In that case you don't need to implement it. You should only implement
it if you've really got something to do.


Brilliant.
Thanks Jon!
Nov 15 '05 #12
> If you need to catch exceptions, then in this case, do not use "using".
Use a try/catch/finally block and make sure you declare your variables
outside of the block and initialized to null (initialize in the block).

Hope this helps.


This is what I currently do but I've been interested in using "using" because it
does seem cleaner.

I've just seen Jon's follow-up post.
I'll try this for a while and see how I get on with it.
Nov 15 '05 #13
wrote:
And the finallizer normally calls dispose (except not the unmanaged
path if you follow the normal pattern for IDisposable)


If you implement the pattern correctly you need the following:

<code>
public class Test : IDisposable
{
~Test()
{
Dispose(false);
}

void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinilize(this);
}

private void Dispose(bool disposing)
{
// do some stuff...
}
}
</code>

--
Greetings
Jochen

Do you need a memory-leak finder ?
http://www.codeproject.com/tools/leakfinder.asp
Nov 15 '05 #14
I think the private Dispose(bool Disposing) method should be protected
virtual, unless your class is sealed.
"Jochen Kalmbach" <no********************@holzma.de> wrote in message
news:Xn*********************************@127.0.0.1 ...
wrote:
And the finallizer normally calls dispose (except not the unmanaged
path if you follow the normal pattern for IDisposable)


If you implement the pattern correctly you need the following:

<code>
public class Test : IDisposable
{
~Test()
{
Dispose(false);
}

void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinilize(this);
}

private void Dispose(bool disposing)
{
// do some stuff...
}
}
</code>

--
Greetings
Jochen

Do you need a memory-leak finder ?
http://www.codeproject.com/tools/leakfinder.asp

Nov 15 '05 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: David N | last post by:
Hi All, I just wonder if in C#, I can develop a user defined control that can call its parent function which is not yet developed. For example, how do I make my user control call a...
24
by: Jazper | last post by:
hi i have this problem. i made a class deverted by CRootItem with implementation of IDisposable-Interface. i made a test-funktion to test my Dispose-Method.... but when set a breakpoint in my...
10
by: Clint | last post by:
Hey all - I'm having a really confusing problem concerning a web service. Right now, I have an application that needs to call a web service that does nothing but return "true" (this will...
15
by: jon | last post by:
How can I call a base interface method? class ThirdPartyClass :IDisposable { //I can not modify this class void IDisposable.Dispose() { Console.WriteLine( "ThirdPartyClass Dispose" ); } } ...
3
by: Giovanni Bassi | last post by:
Hello Group, I am running an operation in a different thread. There are resources that are released when the thread is done running. This is done at the end of the execution as it raises an...
54
by: Zytan | last post by:
I have a log class that makes a synchronized TextWriter like so, in the constructor: StreamWriter sw = new StreamWriter(filename); tw = TextWriter.Synchronized(sw); In the destructor,...
3
by: Rudi | last post by:
Hello, following problem: At program end or release an assembly a serial device should get a final exit sequence. How can I do this? With Dispose() it's no problem, but this assembly is used...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
0
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
1
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.