473,695 Members | 2,767 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 17 '05 #1
25 2371
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 17 '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 17 '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 17 '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 17 '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 17 '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 17 '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 17 '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 17 '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 17 '05 #10

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

Similar topics

8
3409
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:
22
1382
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
8555
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
9112
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
8971
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
8824
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
7651
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
6484
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
5831
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
4336
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...
2
2258
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.