473,396 Members | 1,864 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,396 software developers and data experts.

Why isn't Dispose() implemented in the compiler?

I'm curious if anyone knows why the C# and VB.NET compilers don't
automatically call Dispose() on objects that support IDisposable when they
go out of scope.

I asked a co-worker and his response was that IDisposable is a library
feature and not a language feature. To which I pointed out that the using()
statement calls Dispose() and foreach uses IEnumerator.

So why leave it to developers to screw up when the compiler could
conceivable take care of it for you?

Are there situations when you'd call Dispose() but not want to let the
object go out of scope? I can't think of a single situation. Is there some
other reasoning behind it?

Pete
Nov 16 '05 #1
13 1635
Going out of scope is a hard call my friend. You could pass the object off
somewhere, that holds a reference, or you could get it back from a function
that holds a reference. There are very few cases where you can truly profile
whether an object has gone out of scope. The JITer/GC combo has a better
chance of this because it has reference information as well as scope
information.
That is why the compiler guys leave it to the platform to determine when an
object is out of scope, and languages deal with object references.
--
Justin Rogers
DigiTec Web Consultants, LLC.
Blog: http://weblogs.asp.net/justin_rogers
<pd******@hotmail.com> wrote in message
news:20******************************@news.meganet news.com...
I'm curious if anyone knows why the C# and VB.NET compilers don't
automatically call Dispose() on objects that support IDisposable when they
go out of scope.

I asked a co-worker and his response was that IDisposable is a library
feature and not a language feature. To which I pointed out that the using()
statement calls Dispose() and foreach uses IEnumerator.

So why leave it to developers to screw up when the compiler could
conceivable take care of it for you?

Are there situations when you'd call Dispose() but not want to let the
object go out of scope? I can't think of a single situation. Is there some
other reasoning behind it?

Pete

Nov 16 '05 #2
just to clarify, by scoping rules, I mean variable scopes, not object scopes, which I referred to as object lifetime.

"Daniel Jin" wrote:
because compiler can only resolve simple scoping rules. there's no way a compiler can keep track an object's lifetime, that's the runtime's job. and there is already feature in the runtime to make sure objects get cleaned up correctly (Finalizers).

"pd******@hotmail.com" wrote:
I'm curious if anyone knows why the C# and VB.NET compilers don't
automatically call Dispose() on objects that support IDisposable when they
go out of scope.

I asked a co-worker and his response was that IDisposable is a library
feature and not a language feature. To which I pointed out that the using()
statement calls Dispose() and foreach uses IEnumerator.

So why leave it to developers to screw up when the compiler could
conceivable take care of it for you?

Are there situations when you'd call Dispose() but not want to let the
object go out of scope? I can't think of a single situation. Is there some
other reasoning behind it?

Pete

Nov 16 '05 #3
Hi pdavis68,

You have the answer. The compiler emits calls to Dispose for you, but when
it is safe- when you use *using* operator and there are some other cases the
one I can think of at the moment is at the and of foreach loop it calls
Dispose of the enumerator implements IDisposable

Otherwise is neraly imposible for the compiler to know when an object goes
out of scope. Compiler could easely say when a value type goes out of scope,
but is not likely valuetypes to be disposable. For reference types it is not
that easy because they can be referenced in many places in the code. So the
only one sure thing is that when the GC collects objects. If an object has a
finalizer it is most likely it is disposable as well and the finalizer calls
the dispose method. However this is again resposibilty of the programmer the
compilier cannot do more about it because it has no way to know how the
dispose method is implemented and if it is safe to call it (the object can
be already disposed).

The compiler cannot overdo with the code generated otherwise it could make
the language impossible to use in some scenarios. There some languages with
higher level of abstraction (mostly scrip languages) can do what ever they
want and generate a lot of code, but those languages are specialized in some
degree and their application domain is pretty small.
C# is not that kind of language. It targets wide spectrum of application
(almost any application for .NET platform can be written in C#)

--
HTH
Stoitcho Goutsev (100) [C# MVP]
<pd******@hotmail.com> wrote in message
news:20******************************@news.meganet news.com...
I'm curious if anyone knows why the C# and VB.NET compilers don't
automatically call Dispose() on objects that support IDisposable when they
go out of scope.

I asked a co-worker and his response was that IDisposable is a library
feature and not a language feature. To which I pointed out that the using() statement calls Dispose() and foreach uses IEnumerator.

So why leave it to developers to screw up when the compiler could
conceivable take care of it for you?

Are there situations when you'd call Dispose() but not want to let the
object go out of scope? I can't think of a single situation. Is there some
other reasoning behind it?

Pete

Nov 16 '05 #4
Okay, I see what you're saying. I hadn't thought it through completely.

But then I guess that simply rephrases the question fo why, when something
is marked for garbage collection or even when it's garbage collected, why
not do it there? I think it would make more sense to do it when it's marked
for garbage collection because you generally want to make sure the resources
are freed at that point.

I suppose I can see where you might want to put off disposal, if for some
reason in a particular object, that it's going to be time consuming, but
that seems like such a rare exception that it makes sense to just do it when
it's marked for collection.

Pete

"Justin Rogers" <Ju****@games4dotnet.com> wrote in message
news:er*************@TK2MSFTNGP09.phx.gbl...
Going out of scope is a hard call my friend. You could pass the object off somewhere, that holds a reference, or you could get it back from a function that holds a reference. There are very few cases where you can truly profile whether an object has gone out of scope. The JITer/GC combo has a better
chance of this because it has reference information as well as scope
information.
That is why the compiler guys leave it to the platform to determine when an object is out of scope, and languages deal with object references.
--
Justin Rogers
DigiTec Web Consultants, LLC.
Blog: http://weblogs.asp.net/justin_rogers
<pd******@hotmail.com> wrote in message
news:20******************************@news.meganet news.com...
I'm curious if anyone knows why the C# and VB.NET compilers don't
automatically call Dispose() on objects that support IDisposable when they go out of scope.

I asked a co-worker and his response was that IDisposable is a library
feature and not a language feature. To which I pointed out that the using() statement calls Dispose() and foreach uses IEnumerator.

So why leave it to developers to screw up when the compiler could
conceivable take care of it for you?

Are there situations when you'd call Dispose() but not want to let the
object go out of scope? I can't think of a single situation. Is there some other reasoning behind it?

Pete


Nov 16 '05 #5
<pd******@hotmail.com> wrote:
Okay, I see what you're saying. I hadn't thought it through completely.

But then I guess that simply rephrases the question fo why, when something
is marked for garbage collection or even when it's garbage collected, why
not do it there? I think it would make more sense to do it when it's marked
for garbage collection because you generally want to make sure the resources
are freed at that point.


Well, that's why finalizers often have calls to Dispose. No need for
any magic, and still pretty easy to implement.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6
Yeah, I suppose so and while that helps when you forget, it doesn't obviate
the need for calling Dispose on objects that support IDispose and failing to
do so is considered bad practice and a "leak."

I guess what I'm saying is, it seems that we've traded one problem
(malloc/free or new/delete) for the IDispose issue which we, as programmers,
still need to keep in mind. And in a way, it's even more insidious because
not every object implements it, whereas in C++ for example, you knew, every
object that had a new, needed a matching delete, or every malloc needed a
free.

Don't get me wrong. I've been using C# for over 2 years now and compared to
C++, it's a slice of heaven.

I guess I'm just trying to understand why IDispose isn't dealt with by the
framework/environment automatically, since it seems like something that
would be easily doable and would save us from having to remember to do it.

Pete
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
<pd******@hotmail.com> wrote:
Okay, I see what you're saying. I hadn't thought it through completely.

But then I guess that simply rephrases the question fo why, when something is marked for garbage collection or even when it's garbage collected, why not do it there? I think it would make more sense to do it when it's marked for garbage collection because you generally want to make sure the resources are freed at that point.


Well, that's why finalizers often have calls to Dispose. No need for
any magic, and still pretty easy to implement.

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

Nov 16 '05 #7
"pd******@hotmail.com" wrote:
Okay, I see what you're saying. I hadn't thought it through completely.

But then I guess that simply rephrases the question fo why, when something
is marked for garbage collection or even when it's garbage collected, why
not do it there? I think it would make more sense to do it when it's marked
for garbage collection because you generally want to make sure the resources
are freed at that point.
two major consideration would be performance and resource management.

1. garbage collection is expensive as it halts all execution threads, so you want it to be done and over as quickly as possible.
2. if dispose is not called as soon as possible, it could potentially hold onto valuable resources longer than it needs to, like file handles, database connections. remember, GC is non-deterministic and tied to managed resources only, memory. it won't know that you are running out of file handles or database connections.

I suppose I can see where you might want to put off disposal, if for some
reason in a particular object, that it's going to be time consuming, but
that seems like such a rare exception that it makes sense to just do it when
it's marked for collection.


in case if you are not aware, there is already a mechanism called finalization that run by the GC, but it's still crucial to manually dispose objects when they are no longer used.
Nov 16 '05 #8

"Daniel Jin" <Da*******@discussions.microsoft.com> wrote in message
news:24**********************************@microsof t.com...
"pd******@hotmail.com" wrote:
Okay, I see what you're saying. I hadn't thought it through completely.

But then I guess that simply rephrases the question fo why, when something is marked for garbage collection or even when it's garbage collected, why not do it there? I think it would make more sense to do it when it's marked for garbage collection because you generally want to make sure the resources are freed at that point.
two major consideration would be performance and resource management.

1. garbage collection is expensive as it halts all execution threads, so

you want it to be done and over as quickly as possible. 2. if dispose is not called as soon as possible, it could potentially hold onto valuable resources longer than it needs to, like file handles, database
connections. remember, GC is non-deterministic and tied to managed
resources only, memory. it won't know that you are running out of file
handles or database connections.


Well, this is why I later mentioned you might want to put off disposal for
performance considerations, so I understand the reasoning there, but there's
rarely a time when people do this. You usually call Dispose() as soon as you
can, so it seems to me that in the process of marking an object for garbage
collection, the framework could go ahead and call Dispose() right there. I'm
not saying to then garbage collect it. I'm saying that otherwise you treat
the object like any other object as far as garbage collection.

I guess this is what I'm saying:

You call Dispose() immediately before you release the final reference to an
object. An object is generally useless after Dispose() is called, and it
should certainly be considered so.

When you release the final reference to the object, it is marked as
available for collection. There's no reason to call Dispose() and then hold
onto a reference to the object and you shouldn't release the final reference
to an objec that implements IDisposable without calling Dispose().

So what I'm saying is there's no useful life in an object between the time
Dispose() is called and the final reference is released. So why not call
Dispose() from within the framework at that time?

Pete
Nov 16 '05 #9
"pd******@hotmail.com" wrote:
Well, this is why I later mentioned you might want to put off disposal for
performance considerations, so I understand the reasoning there, but there's
rarely a time when people do this. You usually call Dispose() as soon as you
can, so it seems to me that in the process of marking an object for garbage
collection, the framework could go ahead and call Dispose() right there. I'm
not saying to then garbage collect it. I'm saying that otherwise you treat
the object like any other object as far as garbage collection.

I guess this is what I'm saying:

You call Dispose() immediately before you release the final reference to an
object. An object is generally useless after Dispose() is called, and it
should certainly be considered so.

When you release the final reference to the object, it is marked as
available for collection. There's no reason to call Dispose() and then hold
onto a reference to the object and you shouldn't release the final reference
to an objec that implements IDisposable without calling Dispose().
alright, I see where your confusion is. here's how GC works. .NET framework doesn't use a reference counting technique like COM. so it will never know which reference is the *LAST* reference to the object in memory. so what you are proposing will never work. It relies on the GC to do a sweep once in a while, walking the object graph to determine what's dead and elligble for garbage collection. problem here is, it happens in a non-deterministic manner. so if you don't manually dispose, it could be a *VERY* long time until the GC actually gets to run and dispose it for you, causing a *LEAK* so to speak on limited resource that the runtime is not aware of.

does that explain it for you?
So what I'm saying is there's no useful life in an object between the time
Dispose() is called and the final reference is released. So why not call
Dispose() from within the framework at that time?

Pete

Nov 16 '05 #10
>
alright, I see where your confusion is. here's how GC works. .NET framework doesn't use a reference counting technique like COM. so it will
never know which reference is the *LAST* reference to the object in memory.
so what you are proposing will never work. It relies on the GC to do a
sweep once in a while, walking the object graph to determine what's dead and
elligble for garbage collection. problem here is, it happens in a
non-deterministic manner. so if you don't manually dispose, it could be a
*VERY* long time until the GC actually gets to run and dispose it for you,
causing a *LEAK* so to speak on limited resource that the runtime is not
aware of.
does that explain it for you?


Yes, that explains it perfectly. I was under the impression objects used a
COM style reference count for determining when objects were eligeable for
collection. That not being the case, then it makes perfect sense that you
couldn't automate IDispose calls. Thanks.

Pete
Nov 16 '05 #11
<pd******@hotmail.com> wrote:
Yeah, I suppose so and while that helps when you forget, it doesn't obviate
the need for calling Dispose on objects that support IDispose and failing to
do so is considered bad practice and a "leak."
Indeed.
I guess what I'm saying is, it seems that we've traded one problem
(malloc/free or new/delete) for the IDispose issue which we, as programmers,
still need to keep in mind.
Yes.
And in a way, it's even more insidious because
not every object implements it, whereas in C++ for example, you knew, every
object that had a new, needed a matching delete, or every malloc needed a
free.
Well, that means you need to spend less of your time being careful -
once you know which types implement IDisposable (and you learn *very*
quickly, IME) you can spend most of the time not worrying at all. The
using statement makes it easier to deal with IDisposable objects most
of the time, too.
Don't get me wrong. I've been using C# for over 2 years now and compared to
C++, it's a slice of heaven.

I guess I'm just trying to understand why IDispose isn't dealt with by the
framework/environment automatically, since it seems like something that
would be easily doable and would save us from having to remember to do it.


If you reckon deterministic finalization would be easy to do in a
robust manner, I'm sure Microsoft will hire you in a second :)

(Basically, it can't be done with any kind of efficiency.)

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

Daniel's description of how the garbage collection works has cleared my
understanding of why this can't be done.

My error was in thinking that the garbage collection was using COM style
reference counting to determine when objects were available for collection.
I probably just had that preconceived notion and never paid attention well
enough when reading about garbage collection to question it.

I assume the COM style reference counting isn't used for performance
reasons. Adding reference counting to every object in the system would
probably add up a bit, particularly for smaller objects that are probably
used in great quantities, such as Point and Size structs.

That said, would it be such a terrible price to pay to add reference
counting to IDisposable objects for the express purpose of handling the
Dispose() calls? I don't know. I suppose the hit on GDI+ objects like Pens
and Brushes might be enough to be noticeable.

My general thinking is that there are already so many places that
programmers can make mistakes, it's nice when the language/environment can
remove as many of those situations as possible.

Pete

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
<pd******@hotmail.com> wrote:
Yeah, I suppose so and while that helps when you forget, it doesn't obviate the need for calling Dispose on objects that support IDispose and failing to do so is considered bad practice and a "leak."
Indeed.
I guess what I'm saying is, it seems that we've traded one problem
(malloc/free or new/delete) for the IDispose issue which we, as programmers, still need to keep in mind.


Yes.
And in a way, it's even more insidious because
not every object implements it, whereas in C++ for example, you knew, every object that had a new, needed a matching delete, or every malloc needed a free.


Well, that means you need to spend less of your time being careful -
once you know which types implement IDisposable (and you learn *very*
quickly, IME) you can spend most of the time not worrying at all. The
using statement makes it easier to deal with IDisposable objects most
of the time, too.
Don't get me wrong. I've been using C# for over 2 years now and compared to C++, it's a slice of heaven.

I guess I'm just trying to understand why IDispose isn't dealt with by the framework/environment automatically, since it seems like something that
would be easily doable and would save us from having to remember to do

it.
If you reckon deterministic finalization would be easy to do in a
robust manner, I'm sure Microsoft will hire you in a second :)

(Basically, it can't be done with any kind of efficiency.)

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

Nov 16 '05 #13
<pd******@hotmail.com> wrote in
news:4b******************************@news.meganet news.com:
Jon,

Daniel's description of how the garbage collection works has cleared
my understanding of why this can't be done.

My error was in thinking that the garbage collection was using COM
style reference counting to determine when objects were available for <snip> That said, would it be such a terrible price to pay to add reference
counting to IDisposable objects for the express purpose of handling
the Dispose() calls? I don't know. I suppose the hit on GDI+ objects


One of the problems with reference counting is cyclic references.

If variable V1 holds a reference to object A, and object A has a reference
to object B and object B has a reference back to object A, then clearing
the V1 reference won't remove object A or B since both have 1 reference
left, hence a leak.

--
Lasse Vågsæther Karlsen
http://www.vkarlsen.no/
PGP KeyID: 0x0270466B
Nov 16 '05 #14

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

Similar topics

3
by: faktujaa | last post by:
Hi All, A small confusion. I have defined a connection class that has System.Data.IDbConnection as a member variable and implements IDisposable interface. I have implemented Dispose method to call...
11
by: Ken Durden | last post by:
I am in search of a comprehensive methodology of using these two object cleanup approaches to get rid of a number of bugs, unpleasantries, and cleanup-ordering issues we currently have in our...
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...
11
by: Alexei | last post by:
Hello, The following doesn't compile due to absence of the copy constructor in class FileStream: FileInfo ^ fi = ...; FileStream fs = fi->OpenRead(); The compiler is Beta 2. Is this...
4
by: Joe Abou Jaoude | last post by:
I m preparing to pass the 70-306 exam, so i downloaded Q & A from multiple sites. There's this question that really confuses me, coz i see that both answers A and C are both correct. Can anyone...
6
by: Teresa | last post by:
1) If I do want to keep an object alive throughout the live of an application, how can I ensure that the GC doesn't clean it up? 2a) How do I determine if an object is a managed or an unmanged...
14
by: Jonas | last post by:
Hi! I'm developing the middletiers of an ASP.NET application in VB.NET. I've got a business logic layer in which I would like to perform auditing to a database. Instead of making an auditing...
156
by: Dennis | last post by:
Ok, I'm trying to dispose of every object that I create that has a dispose method based on advice from this newsgroup. However, I'm not sure how to dispose of the following object that was created...
44
by: Smokey Grindle | last post by:
I have a list box on my form, but I need to databind it to a data table that is a private member of the form's class... so I basically have Public Class MyForm priate m_MyTable as new datatable...
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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...

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.