473,795 Members | 2,968 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1660
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******@hotma il.com> wrote in message
news:20******** *************** *******@news.me ganetnews.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******@hotma il.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******@hotma il.com> wrote in message
news:20******** *************** *******@news.me ganetnews.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****@games4d otnet.com> wrote in message
news:er******** *****@TK2MSFTNG P09.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******@hotma il.com> wrote in message
news:20******** *************** *******@news.me ganetnews.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******@hotma il.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.co m>
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.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
<pd******@hotma il.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.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #7
"pd******@hotma il.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*******@disc ussions.microso ft.com> wrote in message
news:24******** *************** ***********@mic rosoft.com...
"pd******@hotma il.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******@hotma il.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

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

Similar topics

3
6077
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 Dispose method of IDbConnection. This Dispose method is called from a destructor. In the dispose method, i also call GC.SuppressFinalize(this) so as to avoid finalizer. All this was OK untill i came across one article that says - not to call...
11
5312
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 4-month old C#/MC++ .NET project project. I'd like to thank in advance anyone who takes the time to read and/or respond to this message. At a couple points, it may seem like a rant against C# / .NET, but we are pretty firmly stuck with this approach...
24
7699
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 Dispose-Method and call the GC nothing happend!!! my Disposemethod has never been called!! so the GC dont call my Dispose-Method although I implemented IDisposable? what am i doing wrong?
11
1309
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 supported? Planned to be supported?
4
5075
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 help me to pick the right answer and explain me why ? thx. Your development team creates an order entry application by using Visual Studio .NET. The application stores and retrieves data in a
6
1810
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 resource? I understand the basic definition for managed resources are resources that the CLR manage and unmanged resources are resources that the CLR doesn't manage, however, I haven't been able to find a concrete answer as to what resources are...
14
1894
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 call in every method of my classes, would it be a workable way to implement IDisposable in the base class to all the BLL-classes and then in the Dispose method to do the audit call? Do I then have to make sure that all uses of the BLL-classes end...
156
5908
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 inside a method call. dim myvar as new object1 object1.dosomethingmethod(new object2) Note that object 2 has a dispose method but how do I dispose of it unless I do the following:
44
8275
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 End Class now where would I properly dispose of this? In the finalize method? I am loading the data for the table in a subroutine that is executed at form load, of course all the commands tied to it are wrapped in using blocks, but
0
10439
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10215
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10165
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10001
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6783
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3727
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.