473,725 Members | 1,735 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on implementing IDisposable

phl
hi,

My question is:

1. To avoid possible memory leaks, when you use this pattern, after you
have dealth with the unmanaged resources and before you take your
object off the finalize queue, how are you sure that your managed
object resources are completely freed up of resources it's might be
using? In my case below I have a private bool variable. Are there any
other managed resource that you might need to explicitly free up in
Dispose?

2. I have the example in msdn that instanciates a Component object but
doesn't actually do anything with it, what is this class for?

Thanks
-phl

Here's some pseudo code:
public classA : IDisposable
{
private Component component = new Component(); //WHAT IS THIS
FOR????
private XmlTextReader reader;
private bool disposed = false;
public LoadFile(string FilePath)
{
reader = new XmlTextReader(F ilePath);
}
public void CloseFile()
{
reader.Close();
}

public void Dispose()
{
Dispose(true);
GC.SuppressFina lize(this);
}
public void Dispose(bool disposing)
{
if (!this.disposed )
{
if (disposing)
{
CloseFile();
//are there anything else you need to free up
here?????
}
}

this.disposed = true;
}

ClassA()
{
Dispose(false);
}
}

May 29 '06 #1
4 3331
"phl" <ki************ @hotmail.com> wrote:

You seem to be confusing two distinct but related topics:

1) Implementing IDisposable so that classes which use other objects as
part of their implementation, which themselves need disposing, can be
disposed of, in a recursive manner.

2) Implementing .NET finalizers, for freeing unmanaged resources, which
also involves implementing IDisposable.
1. To avoid possible memory leaks,
The IDisposable pattern is for resource leaks, typically not memory
leaks.
when you use this pattern, after you
have dealth with the unmanaged resources and before you take your
object off the finalize queue
Now you are talking about finalization - which is something different
from simply implementing IDisposable. Many objects implement IDisposable
to permit closing of files etc. - i.e. deterministic deallocation of
resources used by the class.

That is something *different* from Finalize() (aka ~MyClassName()) ,
which is for unmanaged resources *directly* represented by the managed
class.

You should only need to implement a finalizer (i.e. ~MyClassname()) when
you are wrapping an OS resource.
how are you sure that your managed
object resources are completely freed up of resources it's might be
using?
I don't understand this question, sorry.
2. I have the example in msdn that instanciates a Component object but
doesn't actually do anything with it, what is this class for?
What example, where? I presume it is a *placeholder* for something which
implements IDisposable (Component itself implements IDisposable), such
as a Stream or other resource.
public classA : IDisposable
{
private Component component = new Component(); //WHAT IS THIS
FOR????
I presume it is a placeholder.
private XmlTextReader reader;
private bool disposed = false;
This protects the class from being disposed multiple times. This is to
permit calling Dispose() multiple times - this is not an error.
public LoadFile(string FilePath)
{
reader = new XmlTextReader(F ilePath);
}

public void CloseFile()
{
reader.Close();
}
I don't understand this code, this will throw an exception if LoadFile()
was never called.
public void Dispose()
{
Dispose(true);
GC.SuppressFina lize(this);
This class does not implement a finalizer (i.e. there is no ~classA()
method), so it does not need to call GC.SupressFinal ize().
}

public void Dispose(bool disposing)
The overloaded Dispose which takes a bool argument should be made
virtual and protected. The reason behind this pattern is to centralize
logic for classes that need finalizers (which this class doesn't,
because it only contains other managed resources).

The idea behind this pattern is based on classes that implement a
finalizer, and that thus there are two ways that the Dispose method can
get called:

1) Explicitly via IDisposable.Dis pose().

2) From the finalizer of this class.

When the method is called via IDisposable.Dis pose(), then it needs to
dispose objects it references, as well as its own unmanaged resources.

When the method is called via the finalizer, it shouldn't access objects
it references, since they are dead objects - finalization only occurs
for objects no longer reachable from the main application object graph.

That's why the implementation of this method has the pattern:

---8<---
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// dispose referenced, managed resources
}
// dispose unmanaged, native OS resources
}
--->8---

For future proofness, this pattern is sometimes also used for classes
which don't have a finalizer. The reason this is done is that the class
may have descendants which also need some disposal logic. The idea is
that the descendants can override this protected Dispose method and
perform their disposal of managed resources, before calling the base
class's Dispose(bool). Then, the base class can implement IDispose, so
the subclasses don't (and shouldn't) need to.

Basically, with respect to IDisposable, there are three kinds of
classes:

1) Classes which don't need disposing.

2) Classes which use (i.e. have "ownership" semantics on a private
reference to) objects which need disposing, and therefore need disposing
themselves.

3) Classes which need finalizers, and therefore need disposing for
deterministic cleanup. These classes deal with unmanaged resources, and
thus are extremely rare.

Objects in category 1 don't need to implement IDisposable.

Objects in category 2 and 3 do need to implement IDisposable.

For objects in category 2, the dispose pattern is for future-proofness
and to permit descendants to be disposed when the IDisposable.Dis pose()
method is called via the base class.

For objects in category 3, the dispose pattern is to centralize cleanup
depending on whether the cleanup was invoked via the finalizer, or
directly via the IDisposable.Dis pose() method.

Objects in category 3 are very rare: you are unlikely to be implementing
them unless you are wrapping unmanaged resources, e.g. shared
memory-mapped files or direct hardware access.
{
if (!this.disposed )
{
if (disposing)
{
CloseFile();
//are there anything else you need to free up
here?????
}
}

this.disposed = true;
You don't need to flag the object as disposed if you are simply using
this in the "recursive IDisposable" scenario: i.e. if this class is
implementing IDisposable simply to propagate Dispose() calls to the
inner XmlTextReader, then the flag is not needed. It is safe to call
Dispose() multiple times on the inner XmlTextReader (it's always safe to
call Dispose() multiple times).
}

ClassA()
{
Dispose(false);
}
This is calling Dispose in the constructor? Or is this meant to be a
finalizer?
}


-- Barry

--
http://barrkel.blogspot.com/
May 29 '06 #2
phl
Hi Barry,

Thanks for the great info! Sorry for confusion, on your last question,
the code should be:
~ClassA()
{
Dispose(false);
}


Yes, my CloseFile() routine makes no sense and should be made private.

This is the msdn link
http://msdn.microsoft.com/library/de...classtopic.asp
- inregards to Component Class being used, without much explaination.

What I want to do is release the handle to an opened file, while
implemmenting IDisposable. This is my brief overview of garbage
collection, so correct me if I am wrong. I want to be deterministic
about the closing of my file. To do this I can implement a nice Dispose
pattern using the IDisposable interface. So I go and close my file in
my Dispose method and afterwards call GC.SuppressFina lize(this); . The
way I understand this is that when I call GC.SuppressFina lize(this), I
am telling the framwork to take my object off the finalise queue. So my
concern is if I don't deallocate all memory I have used.... in this
case I have declared also a boolean variable in my class, does the
..net runtime know that it's supposed to free up the memory allocated
for this boolean variable? So by taking my object of the finalise
queue, hence causing to be missed my the garbage collector, do I have
to deallocate every bit of memory I have use?

May 29 '06 #3
"phl" <ki************ @hotmail.com> wrote:
What I want to do is release the handle to an opened file
Presumably opened (ultimately) via FileStream.
, while
implemmenting IDisposable. This is my brief overview of garbage
collection, so correct me if I am wrong. I want to be deterministic
about the closing of my file. To do this I can implement a nice Dispose
pattern using the IDisposable interface. So I go and close my file in
my Dispose method
That is good as far as it goes.
and afterwards call GC.SuppressFina lize(this);
To close a file opened via FileStream, where your object is the only
object which has a reference to this FileStream object, you do not call
GC.SuppressFina lize, because you don't need a finalizer.
. The
way I understand this is that when I call GC.SuppressFina lize(this), I
am telling the framwork to take my object off the finalise queue.
The finalize queue is *only* for objects which implement a finalizer.
Any object which only uses unmanaged resources via managed classes (such
as FileStream) does *not* need to implement a finalizer.
So my
concern is if I don't deallocate all memory I have used....
You don't need to deallocate memory. The GC specifically does this (and
pretty much only guarantees this).
in this
case I have declared also a boolean variable in my class, does the
.net runtime know that it's supposed to free up the memory allocated
for this boolean variable?
You don't need to worry about that. For one thing, the boolean is a .NET
value type and is allocated as part of the object memory, so it will be
fried when the object is freed.
So by taking my object of the finalise
queue, hence causing to be missed my the garbage collector, do I have
to deallocate every bit of memory I have use?


You do not need to implement IDisposable or a finalizer to free memory.
The GC does this for you.

-- Barry

--
http://barrkel.blogspot.com/
May 29 '06 #4
phl
Cheers for taking the time answering, I got it now.

May 30 '06 #5

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

Similar topics

3
4505
by: Ivan Neganov | last post by:
Hi, I have a custom subclass of System.IO.Stream type. I wonder how to correctly implement the IDisposable pattern in this situation. The parent Stream type apparently uses explicit interface implementation, and I could not find a way for my child type to override parent's IDisposable.Dispose() method. The intention was to clean up child's resources first,
2
1700
by: Andrew Quine | last post by:
Hi Short one: looking for a good example and an explanation of such enumerators. I know MessageEnumerator and ResourceReader do this, for example, but what is the implementation of the enumerator doing that needs a Dispose of its own? Cheers! Andrew Quine
9
2025
by: Alvin Bruney [MVP] | last post by:
with the using construct, exit from scope calls dispose on said object. But what happens in a connection pooling scenario? Is the run-time smart enough to realize that Object Pooling is being used so it will not call dispose and instead flag the object similar to what close() does when pooling is in effect. Or does it really go ahead and shut down the object? If it does, then isn't it circumventing the object pooling? Does anybody know? ...
4
1998
by: Joey | last post by:
Hi, I have come across codes like this if(dbConn != null) { dbConn.dispose(); } and sometimes like
11
1341
by: Michael Rodriguez | last post by:
Suppose I have a dataset, dsMain, that is already filled with data. What then, is the affect of this: DataSet ds1 = dsMain; Does this cause ds1 to simply become a pointer to dsMain? If so, how is this code different: DataSet ds1 = new DataSet(); ds1 = dsMain;
7
2093
by: Scott M. | last post by:
In a typical class, do I need to indicate that it implements the IDisposable interface and then create a Dispose method that implements the Dispose required by the IDisposable interface or can I just make a Sub Dispose() and the CLR will know that this is the Dispose method to call when the object falls out of scope? Thanks.
3
8914
by: Senthil | last post by:
Hi , I am learning C# and now am stuck with a simple prorgam.Tried googling but didn't get an answer :(. The following program gives me three compilation errors.Can anyone enlighten me? Thanks. using System; using System.Collections.Generic; using System.Text; namespace Collections
4
1737
by: jmDesktop | last post by:
In the code below from MSDN How do the PeopleEnum methods ever get called? foreach (Person p in peopleList) Console.WriteLine(p.firstName + " " + p.lastName); What is going on behind the scenes in the foreach? Also, I could not find where the interface signatures were for the
0
8872
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
8747
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9392
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
9246
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
9162
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,...
1
6694
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
4505
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...
1
3211
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
2619
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.