473,792 Members | 3,076 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Not axactly a memory leak but can be bad


I finally narrowed down my code to this situation, quite a few (not all) of
my CMyClass objects got hold up after each run of this function via the
simple webpage that shows NumberEd editbox. My memory profile shows that
those instances survive 3 rounds of GC collections - it's not what I
expected. In my real code, CMyClass occupies big amount of memory and they
all share one stance of another class that I don't have enough memory hold
more than a just a few in the memory. Notice that the finalizaer the my
CMyClass makes a big difference in demonstrating this issue, w/o it the
problem doesn't exist. The interesting thing is if I run the page again,
the old dangling ones got destroyed and the new ones become dangling. Am I
missing something about the GC? Do I need to explicitly implement and call
dispose for these classes instead of relying on GC to promptly collect it?
Apparently somehow these objects can survive the automatic
collections...d isposing it would help. Thanks for your comment and help.

internal class CMyClass
{
ArrayList m_array = new ArrayList( 50000 );
private string m_idStr;
private Guid m_guid;
internal CMyClass( int n )
{
for( int i = 0; i < n; ++i )
m_array.Add( Guid.NewGuid() );

m_guid = Guid.NewGuid();
m_idStr = m_guid.ToString ();
}

internal Guid id
{
get{ return (Guid ) m_array[ 0 ]; }
}

~CMyClass()
{
// Trace.Write( m_guid, m_idStr );
}

}
private void RunBtn_Click(ob ject sender, System.EventArg s e)
{
ResultEd.Text = "";
try
{

for( int i = 0; i < int.Parse( NumberEd.Text ); ++i )
{

Hashtable table = new Hashtable( 100 );
ArrayList ids = new ArrayList( 10 );
for( int j = 0; j < 10; ++j )
{
Guid id = Guid.NewGuid();
table[ id ] = null;
ids.Add( id );
}
for( int k=0; k < 10; ++k )
{
foreach( Guid id in ids )
{
table[ id ] = new CMyClass( 10 );
}

CMyClass myobj;
foreach( Guid id in ids )
{
myobj = (CMyClass) table[ id ];
myobj.id.ToStri ng();
}
} // for k
} // for
}
catch( Exception ex )
{
ResultEd.Text = ex.Message + "...CallSTa ck:" +
ex.StackTrace;
}

GC.Collect();
GC.WaitForPendi ngFinalizers();
GC.Collect();

GC.WaitForPendi ngFinalizers();
GC.Collect();

ResultEd.Text = "Done";
}

Nov 19 '05 #1
22 1394
Zeng wrote:
the finalizaer the my
CMyClass makes a big difference in demonstrating this issue, w/o it the
problem doesn't exist.


Actually, the finalizer is the problem. When the GC detects that an
object with a finalizer is garbage, it "resurrects " it and puts it on
a finalization queue, to be finalized by a background thread. When the
finalization thread actually gets to call finalize and remove your
object from the queue, the object is again available for collection.
Of course, it's (probably) now been bumped a generation, and so will
stick around for a while.

// Jon, who's procrastinating a bit today ....

--

www.midnightbeach.com
Nov 19 '05 #2

"Zeng" <Ze******@hotma il.com> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..

I finally narrowed down my code to this situation, quite a few (not all)
of
my CMyClass objects got hold up after each run of this function via the
simple webpage that shows NumberEd editbox. My memory profile shows that
those instances survive 3 rounds of GC collections - it's not what I
expected. In my real code, CMyClass occupies big amount of memory and
they
all share one stance of another class that I don't have enough memory hold
more than a just a few in the memory. Notice that the finalizaer the my
CMyClass makes a big difference in demonstrating this issue, w/o it the
problem doesn't exist.


Why do you have a finalizer in the first place, classes having finalizers
need at least two sweeps to be collected.

Willy.
Nov 19 '05 #3


"Willy Denoyette [MVP]" wrote:
Why do you have a finalizer in the first place, classes having finalizers
need at least two sweeps to be collected.


The main reason IMO is CYA when unmanaged resources are involved. The
intent should always be to use Dispose to clean them up asap but if you
forget, or the person who has to maintain your code a year after you've left
doesn't realize he needs to, finalize will make sure it's cleaned up
eventually.
Nov 19 '05 #4

"Dan Neely" <Da******@discu ssions.microsof t.com> wrote in message
news:0B******** *************** ***********@mic rosoft.com...


"Willy Denoyette [MVP]" wrote:
Why do you have a finalizer in the first place, classes having finalizers
need at least two sweeps to be collected.


The main reason IMO is CYA when unmanaged resources are involved. The
intent should always be to use Dispose to clean them up asap but if you
forget, or the person who has to maintain your code a year after you've
left
doesn't realize he needs to, finalize will make sure it's cleaned up
eventually.


I know, but in this case the CMyClass class doesn't implement IDisposable,
doesn't hold any unmanaged resouces and has a completely redundant empty
Finalizer.

Willy.


Nov 19 '05 #5
Is there a way to force the collection on those objects with a finalizer?
From all the documentation I've been reading (not enough reading)
GS.Collect() would do it, then I found some place that calling Collect()
then call WaitForPendingF inalizers() then Collect() again would do it, now I
found that it doesn't do it either. Disposing would just help freeing memory
from unmanaged resources, if all the stuff that occupy memory are in the
managed classes, it would be a problem w/o a way to force collection.


"Jon Shemitz" <jo*@midnightbe ach.com> wrote in message
news:43******** ******@midnight beach.com...
Zeng wrote:
the finalizaer the my
CMyClass makes a big difference in demonstrating this issue, w/o it the
problem doesn't exist.


Actually, the finalizer is the problem. When the GC detects that an
object with a finalizer is garbage, it "resurrects " it and puts it on
a finalization queue, to be finalized by a background thread. When the
finalization thread actually gets to call finalize and remove your
object from the queue, the object is again available for collection.
Of course, it's (probably) now been bumped a generation, and so will
stick around for a while.

// Jon, who's procrastinating a bit today ....

--

www.midnightbeach.com

Nov 19 '05 #6
Zeng wrote:
Is there a way to force the collection on those objects with a finalizer?
Why do you want to? (Fwiw, we usually want to avoid finalization,
because resurrection (and memory use that's higher than necessary for
longer than necessary) is not free. This is the point of IDisposable
and the "using" statement. Write a finalizer to do any necessary
cleanup, in case someone forgets to call Dispose; and call
GC.SuppressFina lize in the Dispose() routine, to avoid finalization
costs.)
if all the stuff that occupy memory are in the
managed classes, it would be a problem w/o a way to force collection.


"Would be"? Or "is"? Some very bright people worked very hard on the
garbage collector - it works awfully well, and you almost never need
to "force" it to do anything.

--

www.midnightbeach.com
Nov 19 '05 #7
I wouldn't need to force it if I know for sure that they will be collected
before the asp.net process gets recycled because it reaches maximum % of
memory in the system (the default is 60%). Does anybody know for sure?
thanks!

"Jon Shemitz" <jo*@midnightbe ach.com> wrote in message
news:43******** *******@midnigh tbeach.com...
Zeng wrote:
Is there a way to force the collection on those objects with a
finalizer?
Why do you want to? (Fwiw, we usually want to avoid finalization,
because resurrection (and memory use that's higher than necessary for
longer than necessary) is not free. This is the point of IDisposable
and the "using" statement. Write a finalizer to do any necessary
cleanup, in case someone forgets to call Dispose; and call
GC.SuppressFina lize in the Dispose() routine, to avoid finalization
costs.)
if all the stuff that occupy memory are in the
managed classes, it would be a problem w/o a way to force collection.


"Would be"? Or "is"? Some very bright people worked very hard on the
garbage collector - it works awfully well, and you almost never need
to "force" it to do anything.

--

www.midnightbeach.com

Nov 19 '05 #8

"Zeng" <Ze******@hotma il.com> wrote in message
news:uI******** ******@TK2MSFTN GP14.phx.gbl...
I wouldn't need to force it if I know for sure that they will be collected
before the asp.net process gets recycled because it reaches maximum % of
memory in the system (the default is 60%). Does anybody know for sure?
thanks!


Yes, for sure the GC runs more often that you ever imagine.

Willy.
Nov 19 '05 #9
and just to add my two pennies worth ...

Although you may call GC.Collect(), much the same as in Java when you try to
force the VM to run garbage collection, it will still run at it's earliest
convenience.

During compilation, your code is injected with "safe points" whereby the GC
can hijack the thread and take control to do its work. Now, when you call
GC.Collect() your code might not be in a stable enough state for the GC to
run, and the only way that the GC can know that it is safe to run is if it
has reached a "safe point".

Generally speaking, it is bad practice to call GC.Collect() since you will
inadvertantly interrupt a perfectly (or near to) working system, and you
yourself can cause all sorts of naughtiness to occur.

My choice of preference (as it is for a lot of developers) is to implement
IDisposable.

AND, yes, our code should be easily readable and left in a state that
renders it possible for future devlopers to look at it and see what is going
on (for maintenance reasons, or whatever), however, designing our classes
"off centre" just in case, the next developer doesn't know as much as us is a
pretty poor choice IMHO.

--
Of all words of tongue and pen, the saddest are: "It might have been"

Bill.Richards @ greyskin .co .uk
http://greyskin.co.uk
"Zeng" wrote:

I finally narrowed down my code to this situation, quite a few (not all) of
my CMyClass objects got hold up after each run of this function via the
simple webpage that shows NumberEd editbox. My memory profile shows that
those instances survive 3 rounds of GC collections - it's not what I
expected. In my real code, CMyClass occupies big amount of memory and they
all share one stance of another class that I don't have enough memory hold
more than a just a few in the memory. Notice that the finalizaer the my
CMyClass makes a big difference in demonstrating this issue, w/o it the
problem doesn't exist. The interesting thing is if I run the page again,
the old dangling ones got destroyed and the new ones become dangling. Am I
missing something about the GC? Do I need to explicitly implement and call
dispose for these classes instead of relying on GC to promptly collect it?
Apparently somehow these objects can survive the automatic
collections...d isposing it would help. Thanks for your comment and help.

internal class CMyClass
{
ArrayList m_array = new ArrayList( 50000 );
private string m_idStr;
private Guid m_guid;
internal CMyClass( int n )
{
for( int i = 0; i < n; ++i )
m_array.Add( Guid.NewGuid() );

m_guid = Guid.NewGuid();
m_idStr = m_guid.ToString ();
}

internal Guid id
{
get{ return (Guid ) m_array[ 0 ]; }
}

~CMyClass()
{
// Trace.Write( m_guid, m_idStr );
}

}
private void RunBtn_Click(ob ject sender, System.EventArg s e)
{
ResultEd.Text = "";
try
{

for( int i = 0; i < int.Parse( NumberEd.Text ); ++i )
{

Hashtable table = new Hashtable( 100 );
ArrayList ids = new ArrayList( 10 );
for( int j = 0; j < 10; ++j )
{
Guid id = Guid.NewGuid();
table[ id ] = null;
ids.Add( id );
}
for( int k=0; k < 10; ++k )
{
foreach( Guid id in ids )
{
table[ id ] = new CMyClass( 10 );
}

CMyClass myobj;
foreach( Guid id in ids )
{
myobj = (CMyClass) table[ id ];
myobj.id.ToStri ng();
}
} // for k
} // for
}
catch( Exception ex )
{
ResultEd.Text = ex.Message + "...CallSTa ck:" +
ex.StackTrace;
}

GC.Collect();
GC.WaitForPendi ngFinalizers();
GC.Collect();

GC.WaitForPendi ngFinalizers();
GC.Collect();

ResultEd.Text = "Done";
}

Nov 19 '05 #10

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

Similar topics

8
3414
by: ranjeet.gupta | last post by:
Dear All Is the Root Cause of the Memory corruption is the Memory leak, ?? suppose If in the code there is Memory leak, Do this may lead to the Memory Corruption while executing the program ? In nut shell, what is/are the realtion/s between the Memory Leak and Memory Corruption. Juts Theoritical Assumtion below:
25
2388
by: Zeng | last post by:
I finally narrowed down my code to this situation, quite a few (not all) of my CMyClass objects got hold up after each run of this function via the simple webpage that shows NumberEd editbox. My memory profile shows that those instances survive 3 rounds of GC collections - it's not what I expected. In my real code, CMyClass occupies big amount of memory and they all share one stance of another class that I don't have enough memory hold...
0
9670
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
10430
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
10211
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...
0
9033
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...
0
6776
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
5436
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
5560
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4111
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
3719
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.