473,405 Members | 2,445 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 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 6693
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.