473,748 Members | 3,107 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dispose(bool), Idisposable, form closing etc.

Hello,

I am confused by dispose etc. and hope someone can set me right.

1. The Dispose(Bool) the IDE generates for a form has nothing to do
with IDisposable, right?
2. So when is this called? When a form is closed? If this is caused
automatically when a form is closed how can I then access things on a
modal from after ShowDialog() returns? Or is it only for modeless
forms?
3. Does the garbage collector automically call Dispose() which is part
of IDisposable when an onbject is garbage collected? I know this is
non-deterministic etc. Is this what is known as the Finalizer or
whatever it's called?
4. I don't understand how garbage collection works with forms. If I
have a method which declares a variable which is a form, and
instantiate it in the same routine, when I leave the routine the
variable is released, the form's reference count should then be zero
and therefore a candiate for garbage collection, no? Is there another
refernce to it somewhere?

Confused,

Ray

Nov 19 '07 #1
19 4646
On 2007-11-19 12:14:30 -0800, rbrowning1958 <RB***********@ gmail.comsaid:
Hello,

I am confused by dispose etc. and hope someone can set me right.

1. The Dispose(Bool) the IDE generates for a form has nothing to do
with IDisposable, right?
I wouldn't go that far. It's not part of the interface, but it is part
of the common implementation of the interface.
2. So when is this called? When a form is closed? If this is caused
automatically when a form is closed how can I then access things on a
modal from after ShowDialog() returns? Or is it only for modeless
forms?
Forms shown with ShowDialog() are not disposed when they are closed.
3. Does the garbage collector automically call Dispose() which is part
of IDisposable when an onbject is garbage collected? I know this is
non-deterministic etc. Is this what is known as the Finalizer or
whatever it's called?
If you have not called Dispose(), then the finalizer won't be
suppressed and the finalizer may eventually be called. The object
cannot be collected until the finalizer is run (for objects that have a
finalizer and don't suppress finalizing).
4. I don't understand how garbage collection works with forms.
It works the same as for other classes that implement IDisposable.
If I
have a method which declares a variable which is a form, and
instantiate it in the same routine, when I leave the routine the
variable is released, the form's reference count should then be zero
and therefore a candiate for garbage collection, no? Is there another
refernce to it somewhere?
There's no referencing counting.

As far as eligibility for garbage collection goes, what matters is
where there's a reference to the form somewhere else. In the case of a
form, its instance is added to the application's list of open forms,
which you can retrieve from the Application.Ope nForms property.

So, yes...there's still a reference to the form somewhere.

Pete

Nov 19 '07 #2
On Nov 19, 2:14 pm, rbrowning1958 <RBrowning1...@ gmail.comwrote:
Hello,

I am confused by dispose etc. and hope someone can set me right.

1. The Dispose(Bool) the IDE generates for a form has nothing to do
with IDisposable, right?
Well, it is related because that is required for the canonical
implemenation of IDisposable. But, you are correct. There is no
strict relationship between Dispose(bool) and IDisposable.
2. So when is this called? When a form is closed? If this is caused
automatically when a form is closed how can I then access things on a
modal from after ShowDialog() returns? Or is it only for modeless
forms?
It is called when either the IDisposable.Dis pose method is called from
user code or as a last resort by the GC when Finalize is called. It's
been awhile, but I don't think closing a modal form disposes it.
Furtheremore, some (most?) class authors choose to allow property
getters to return even after the object has been disposed.
3. Does the garbage collector automically call Dispose() which is part
of IDisposable when an onbject is garbage collected? I know this is
non-deterministic etc. Is this what is known as the Finalizer or
whatever it's called?
The GC will not call IDisposable.Dis pose. However, it may indirectly
call Dispose(bool) because it's part of the Finalize method
(destructor in C#)...at least if you've choosen the canonical
implementation of IDisposable.
4. I don't understand how garbage collection works with forms. If I
have a method which declares a variable which is a form, and
instantiate it in the same routine, when I leave the routine the
variable is released, the form's reference count should then be zero
and therefore a candiate for garbage collection, no? Is there another
refernce to it somewhere?
No, there is no reference counting involved. Assuming the form
doesn't somehow register itself in a static data structure then it
should be a candidate for garbage collection once it falls out of
scope.
>
Confused,

Ray
Nov 19 '07 #3
Ray,

See inline:
Thank you all for replying I've arbitrarily chosen yours to reply to,
Nicholas.
I'm flattered =P
So let me see if I have this right:

1. Dispose(Bool) as part of a form is not explicitly part of the
IDisposable interface, but the implementation of IDisposable,Dis pose
further up the class hierarchy (form I suppose) calls this. This is
waht Brian called the Canonical implementation (I never did understand
what that word meant!).
Yep.
2, When a modeless form is called, clicking the form's close button,
or calling the close() method calls IDisposable.Dis pose which in turn
calls Dispose(bool).
Yep.
3. If it's a modal form, clicking the close button or calling the
close method just hides the form, and does not call
IDisposable.dis pose. Therefore I have to do it myself or use a Using
clause.
Yep.
4. A form's destructor will call Dispose(bool) although in most cases
it will not do much because it will already have been called by
IDisposable.dis pose. SO...I'm guessing that Idisposable calls
dispose(true), whereas the destructor calls Dispose(false)?
Yep.
5. With regard to garbage collecting - doesn't Peter have it correct
where he says the form is not garbage collected because it is
referenced by application.ope nForms?
Yep.
6. Brian mentioned that some class authors write property getters to
return data even after the form has been destroyed - I don't
understand this. Doesn't this mean the property getter has to be
static - and where would it savbe the data? In static class vars? That
implies I only have one instance of the form, right?
No. The properties would be instance, and you would access them off the
form instance before you call Dispose on the form. You ^could^ get away
with accessing the properties after dispose is called, but only if they are
fields that store data that is not dependent on accessing the disposed form
itself.

For example, if you had a text box with text in it, and then you showed
the form modally, if you expose the text in the textbox in a property by
calling the Text property on the textbox, you will get an exception if you
try to access that property after the form is disposed (since the textbox is
disposed of as well). However, if you store the contents of the TextBox in
a string before you dispose of the form, and then access the string in the
property, you won't have a problem, even if the form is disposed.

However, I don't think you should worry about transferring all of your
control values to fields (instead of accessing the values on the controls
from the properties/methods), as it's completely reasonable to expect that
your object won't work once disposed.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
>
Thanks everbody,

Best

Ray

Nov 20 '07 #4
"rbrowning1 958" <RB***********@ gmail.comschrie b im Newsbeitrag
news:db******** *************** ***********@41g 2000hsh.googleg roups.com...
>
6. Brian mentioned that some class authors write property getters to
return data even after the form has been destroyed - I don't
understand this. Doesn't this mean the property getter has to be
static - and where would it savbe the data? In static class vars? That
implies I only have one instance of the form, right?
Dispose does not delete the instance. It only frees, what should not wait
for the GC to be freed. The fields of the instance still live on, until the
instance is collected. So any propertie, that does not depend on the 'open
state' of the form will be accessible. This includes all properties that
simply access fields. But, in case of a form, you can't access f.e. the
controls of the form (or at least, you shouldn't count on).
If the form is destroyed in the sense, that it is collected, than there is
no reference to the instance left (if the GC worked right ;-) ), and so no
member of the instance can be accessed.

Christof

Nov 20 '07 #5
"rbrowning1 958" <RB***********@ gmail.comwrote in message
news:db******** *************** ***********@41g 2000hsh.googleg roups.com...
5. With regard to garbage collecting - doesn't Peter have it correct
where he says the form is not garbage collected because it is
referenced by application.ope nForms?
I'm just guessing here but I'd imagine that application.ope nForms keeps what
is called a weak reference to the form. This means that if all other
references are dropped then the GC can kill the references in openForms.
6. Brian mentioned that some class authors write property getters to
return data even after the form has been destroyed - I don't
understand this. Doesn't this mean the property getter has to be
static - and where would it savbe the data? In static class vars? That
implies I only have one instance of the form, right?
No, they are instance members. Remember the form is only hidden so
everything can be accessed still

Michael
Nov 20 '07 #6
On 2007-11-20 15:50:15 -0800, "Michael C" <mi**@nospam.co msaid:
"rbrowning1 958" <RB***********@ gmail.comwrote in message
news:db******** *************** ***********@41g 2000hsh.googleg roups.com...
>5. With regard to garbage collecting - doesn't Peter have it correct
where he says the form is not garbage collected because it is
referenced by application.ope nForms?

I'm just guessing here but I'd imagine that application.ope nForms keeps what
is called a weak reference to the form. This means that if all other
references are dropped then the GC can kill the references in openForms.
No, that's not true. If it were, forms applications would be in a
world of hurt. After all, they by default all start out like this:

void Main()
{
...
Application.Run (new Form1());
}

At a minimum, in the Run() method, there'd have to be some strong
reference to the parameter passed in. But more significantly, this
sort of code:

void button1_Click(o bject sender, EventArgs e)
{
Form2 form2 = new Form2();

form2.Show();
}

which is quite common, would never work if what you say is true.

No, I believe that the list that is exposed as Application.Ope nForms is
a list of plain old strong references. The application code itself is
not required to maintain a reference, so there must be a strong
reference somewhere else and the underlying list implementing OpenForms
is the most likely source.

Now that VS2008 is out, it's only a matter of time before you can go
look yourself if you don't believe me. :) In the meantime, you could
get Reflector and look at the implementation. I've never tried it
myself, but I'm confident at what I might find should I try. Weak
references just wouldn't do the job.

Pete

Nov 21 '07 #7
On Nov 20, 5:21 am, rbrowning1958 <RBrowning1...@ gmail.comwrote:
1. Dispose(Bool) as part of a form is not explicitly part of the
IDisposable interface, but the implementation of IDisposable,Dis pose
further up the class hierarchy (form I suppose) calls this. This is
waht Brian called the Canonical implementation (I never did understand
what that word meant!).
I used the word canonical to mean an authorized, well-established
pattern.
2, When a modeless form is called, clicking the form's close button,
or calling the close() method calls IDisposable.Dis pose which in turn
calls Dispose(bool).

3. If it's a modal form, clicking the close button or calling the
close method just hides the form, and does not call
IDisposable.dis pose. Therefore I have to do it myself or use a Using
clause.

4. A form's destructor will call Dispose(bool) although in most cases
it will not do much because it will already have been called by
IDisposable.dis pose. SO...I'm guessing that Idisposable calls
dispose(true), whereas the destructor calls Dispose(false)?

5. With regard to garbage collecting - doesn't Peter have it correct
where he says the form is not garbage collected because it is
referenced by application.ope nForms?

6. Brian mentioned that some class authors write property getters to
return data even after the form has been destroyed - I don't
understand this. Doesn't this mean the property getter has to be
static - and where would it savbe the data? In static class vars? That
implies I only have one instance of the form, right?
I don't think I was very clear. What I meant was that you may still
be able to call some property getters without them throwing exceptions
even after Dispose has been called on the object. That's because
property getters are usually nothing more than trivial wrappers around
instance variables.
Nov 21 '07 #8
"Peter Duniho" <Np*********@Nn OwSlPiAnMk.comw rote in message
news:2007112017 431716807-NpOeStPeAdM@NnO wSlPiAnMkcom...
No, that's not true. If it were, forms applications would be in a world
of hurt. After all, they by default all start out like this:

void Main()
{
...
Application.Run (new Form1());
}
That wouldn't be a problem because application.Run would keep a reference.
Although you're probably right about everything else. I guess the form must
remove itself from the collection at some point.

Michael
Nov 21 '07 #9
On 2007-11-20 20:06:22 -0800, Peter Duniho <Np*********@Nn OwSlPiAnMk.coms aid:
[...]
>Although you're probably right about everything else. I guess the form must
remove itself from the collection at some point.

I'm sure that when the form is actually disposed, it removes itself
from the open forms list.

Assuming this is true, it's also a highlight as to why it's so
important to dispose forms shown modally when you're done with them.
For many managed types that implement IDisposable, if you forget to
dispose them eventually it's likely that the finalizer will catch up
and go ahead and do that work for you.

But if a form isn't removed from the open forms list until it's
disposed, and a form isn't eligible for garbage collection until it's
removed from the open forms list, then a modal form that you don't
dispose will _never_ be garbage collected. It's a very serious
resource leak, much more so than the usual "didn't dispose" kind of bug.

Though, I admit I don't really know the details. Now I'm curious, so
if I get a moment I'll actually test it and see if I can figure out
what's going on.
So, I went ahead and checked this. Turns out, even a modal form is
removed from the open forms list when it's closed, even if not disposed.

So there's no really scary anti-finalizer bug you can create in your
application with Form.ShowDialog (). Which is not to say that you
should ignore the requirement to dispose a modal form when you're done
with it. Just that it's likely to eventually get disposed via the
usual finalizer "back-up" procedure even if you don't dispose it.

Pete

Nov 21 '07 #10

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

Similar topics

4
4955
by: Andreas Huber | last post by:
Hi there Is there a reason why .NET framework base classes implementing IDisposable (like e.g. System.ComponentModel.Component) do not prevent multiple calls to the protected virtual void Dispose( bool disposing ) function? Derived classes would then no longer need to check whether they have been disposed already and the associated bool member wouldn't be necessary either.
11
5311
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...
14
3130
by: qrli | last post by:
I used to think that all objects that implement IDisposable should be disposed. But I found 80% of the classes implement IDisposable. But when I looked into the samples, most objects are not disposed. Generally, they're Gdi objects, form controls, most components, etc. So why? How can I decide to dispose or not?
6
2157
by: TB | last post by:
I understand the basics of finalization and implementing IDisposable and how one is guaranteed access to managed objects only when working through the IDisposable interface. My question is to what extent can I rely on access to my private data during the finalization process when *not* coming through the IDisposable interface? Are private members still valid or are they managed objects that may already be gone? Are some types accessible...
4
6730
by: Sunit Joshi | last post by:
Hello All I have an abstract class C1 with this: public abstract class C1 { protected bool m_Dirty; protected override void Dispose(bool disposing) { if(m_Dirty) WriteOuput();
7
4464
by: Tamir Khason | last post by:
I have a class public class Foo { public Foo() { DoSomething() } } I want to be able to do something else while the class enters GC - no more
3
2078
by: Maxim | last post by:
Hi! According to documenation, if we need to release some umanaged resources manually, we need to implement IDisposable interface with single Dispose method. I am just wondering, what will happen if I just create my own Dispose (or any other name) mehtod, without implementing the IDisposable interface. In all the examples, which I found, this Dispose method called from my user code (not by GC). What do I miss? Thanks.
3
4380
by: AlexS | last post by:
When I implement Dispose pattern in object implementing IDisposable, current fxcop recommends: Ensure that Wrapper.Dispose():Void is declared as public and sealed. However, if I do as it asks, compiler complains that sealed can't be used because method is not overrideable. I believe sealed isn't applicable here at all. And this rule shouldn't be public virtual in this case.
6
23370
by: =?Utf-8?B?VmljdG9y?= | last post by:
Hi, I have a UserControl (C# WinFroms application) that requires some cleaning code to run when a form with control is closed. Where I can put that code? There is no ControlClosing or ControlClosed event. I can put my code into UserControl.Desgner.cs Dispose method, but that seems to be a bad practive. What do I do?
0
8987
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9366
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
9316
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
9241
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
8239
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6793
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6073
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();...
1
3303
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2777
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.