473,804 Members | 3,802 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
22 1396
From this paragraph:
Garbage collection is triggered in .NET either by application shutdown, heap exhaustion, or an explicit call GC.Collect(). With the exception of
application shutdown, however, garbage collection only occurs when the
execution path reaches a safe point.
Does that mean it's possible for my process to get recycled for reach memory
max% even though most of the memory counted as used is no longer needed by
my app and it is not freed because GC hasn't gotten a chance to do so
safely? If that's true, sounds to me that having a finalizer in my class or
not would only *reduce* the chance of that occuring, but not eliminating, is
that accessment accurate to you?

"billr" <bi***@discussi ons.microsoft.c om> wrote in message
news:DA******** *************** ***********@mic rosoft.com... I guess it's time for me to make my apologies. The point of my mentioning
Safe Points was to illustrate the workings of the GC.

Safe Points are points in the code that have been identified as it being
safe for the GC to suspend ALL threads in order to do its thing.

A problem faced by the GC is that when compacting the heap it must make sure that it does not change the structure of the object graphs (internal
tree-like structures used for determining reachable/non-reachable objects
i.e. referenced/non-referenced objects), nor should it change the structure of the heap. In order to achieve this, the GC is responsible for maintaining object references (i.e. adjusting references within objects contained within the graphs), because of course, when an object is moved in the heap, any
existing references to that object will be invalid. The only safe way to cope with this is to suspend all application threads during garbage collection. It is for this reason that the JIT compiler inserts Safe Points into the code, i.e. points in the execution path that are safe for thread suspension.

Garbage collection occurs by the GC effectively "hijacking" the thread by
inserting a different return address from the safe point. When GC is
complete, .NET sends the thread back to its original return address and
normal execution continues.

Garbage collection is triggered in .NET either by application shutdown, heap exhaustion, or an explicit call GC.Collect(). With the exception of
application shutdown, however, garbage collection only occurs when the
execution path reaches a safe point.

IMPORTANT NOTE :
=============== =

When the GC has determined that an object is in fact garbage, the first
thing it does is check the object's metadata, and if the object implements
Finalize(), instead of destroying the object, it is marked as reachable
(which is not what you want if you want your object to be destroyed
immediately) and is moved from its original graph to another graph called the "finalized queue". A seperate thread then iterates over the finalized queue invoking Finalize() on all objects contained therein; then -and only then-
are the objects removed from the queue and destroyed, hence freeing up its
heap space.

So, essentially, when you implement Finalize() you are telling the GC that
when the object is no longer referenced it is NOT SAFE for deletion YET, and Finalize() must first be invoked, which means that the object is not
destroyed for approximately two runs of garbage collection. It is for this
reason that deterministic finalization is recommended.

EXPLICIT garbage collection is not recommended becuase it is an expensive
operation involving scanning object graphs, thread suspension and resumption, thread context switches, and EXTENSIVE use of reflection to read the objects' metadata.

I hope that that clears up the confusion I might have injected into the
discussion, also, I hope it clears up why you should not declare a finalizer, even if there is no body. The simple act of declaring a finalizer ensures
that the object lives for longer than you might actually intend/require.

--
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'm not sure on what you mean by "there is no documentation
available...bec ause they don't apply here...". The existance of a document doesn't depend on what part of version of my code was posted. I appreciate your help looking into this for me, many people would just ignore posts and move on even they know the answer or have some comments, but I don't think we are going anywhere with it. My response was to BillR who proposes that I should be implementing the IDisposable.

It's the production environment, if the process get recycled, all my cache in the memory will have to be reloaded when it goes back up. That would
cause delay to the service that we want to provide. Sounds like you are not familiar with the processModel entry with attribute memoryLimit="60 " as
default, it's in the machine.config file. thanks!
"Willy Denoyette [MVP]" <wi************ *@telenet.be> wrote in message
news:O5******** *****@TK2MSFTNG P15.phx.gbl...
Again, you don't have to implement IDisposable when you don't deal with managed resources. What do you expect to do in your Dispose method? And No there is no documentation available on Safe points, because they don't

apply
here (at least not in the code snip you've posted).
I'm also not clear on what you mean with recycling the asp.net process,
is
this something you intend to do or is it something that you are
expecting to
be done automatically, anyway before the asp.net process recycles,
all application domains get unloaded, and this implies a GC run and a

finalizer
run, so all objects (still referenced too) will be collected , but even when
some objects aren't collected, all memory once allocated for the
process will return to the OS when the process ends. So what are you afraid of?

Willy.

"Zeng" <Ze******@hotma il.com> wrote in message
news:uX******** ******@tk2msftn gp13.phx.gbl...
> Relying on IDisposable won't work easily in the multi-threading

scenarios.
> Since the memory required for each object is big, I have put them on
> static
> variable to share it among the servicing threads. Think of CMyClass is a > spell-grammar-checker that helps looking up things and provide

suggestions
> for correction for many users create their documents online. In this > scenario, looks like there is the only choice
> --> Make CMyClass disposable and create managing component (internal or > external to the class) just to coordinate when and which objects are

done
> just to call Dispose. This sounds like the intensive plumbing and
> error-prone approach that I was so used to with C++
>
> Conceptually, this is the drawback of a smart system, the programmer

knows
> what he/she needs to be done but can't change its behavior (which is

very
> very smart most of the time)
>
> By the way, where can I find a documentation about the safe-points?
> Wouldn't that be better that there is a call to wait for the system to be
> done with collection and there is a safe point in that method? And
is > there
> a safe point in the component that checks for memory usage and recycle the
> aspnet process when 60%(default) is reached?
>
>
>
> "billr" <bi***@discussi ons.microsoft.c om> wrote in message
> news:3B******** *************** ***********@mic rosoft.com...
>> 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 #21
I'm asking you the same question as I have asked BillR:

Is it possible for my process to get recycled because it reaches memory
max% even though most of the memory counted as used is no longer needed by
my app and it is not freed because GC hasn't gotten a chance to do so
safely? If that's true, sounds to me that having a finalizer in my class or
not would only *reduce* the chance of that occuring, but not *eliminate*, is
that accessment accurate to you?

By the way, I hope I don't need to correct all my mis-understanding what the
GC is meant for to raise that question.

"Willy Denoyette [MVP]" <wi************ *@telenet.be> wrote in message
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..
Seems like you have a fundamental mis-understanding on what the GC is meant for and how it's actually performing.
The GC's task is, to collect the memory space occupied by non-reachable
objects and compact the generation it is actually collecting, so that a
contiguous free space remains in the heap to add new objects.
A full GC is a GC run that collects all generations, the current version of the CLR has 3 generational logical heaps plus a separate large object heap
(LOH), from code you can ask for a GC run by calling GC.Collect(n) where n
indicates the generation to end with, a collection always starts with
generation 0.
GC.Collect() collects all generations plus the LOH, that's why it's called a full collect.

However, it's NOT the task of the GC to bring down the heap size, that's the task of the CLR memory manager , or the hosting process memory manager (if
any) in close cooperation with the OS.

Your code sample needs at least two GC.Collect() calls, that's because you
have a Finalizer (destructor in C# parlance).
When an instance of a finalizable object gets instantiated, it's registered as finalizable.
When it is no longer rooted at the next GC run, it will be moved to the
finalizable queue, where it stays until after the finalizer has run, after
which it's removed from the finalizer queue and it becomes eligible for
collection.
Note that it's possible that not all finalizables are immediately finalized, all depends on the load of the system and the time the finalizer thread
spends finalizing objects. The finalizer thread can be suspended before all finalizer have run, that's why we say at LEAST 2 GC runs, and why we suggest against destructors in C#.

Willy.

PS I suggest you start reading these (somewhat outdated) articles , before
you start arguing about a subject you don't seem to fully understand.
http://msdn.microsoft.com/msdnmag/is...I/default.aspx
http://msdn.microsoft.com/msdnmag/is...2/default.aspx

"Zeng" <Ze******@hotma il.com> wrote in message
news:eq******** ******@TK2MSFTN GP14.phx.gbl...
From what I understand, Dispose method doesn't help freeing manage
resources, and that's consistent with what you are saying.

About the hosting process tries to do a full GC run before it recycles
based
on MemoryLimit%; I don't believe it at this point, if there is such thing as
full GC and it's doing what we expect, then it should have been exposed so we - developers - can call it when we need to bring down the heap size
immediately (of course we don't need this if full GC is actually possible privately to the framework, but I don't believe it). How many times
should
I try to call GC.Collect to free the dangling objects in my demo code?
And
if GC.Collect doesn't do what "Collect" means, what is its use? Purely
advertising?

Imagine somebody sell you a cabinet and there is knob on it, and he tells you that yes that's a knob but don't use it, you NEVER need or want to use it. If you actually never need to use it then it should be only for
decoration :) but that was only a speculation - and one day you decide to pull or turn it, and it doesn't do anything ... hahaha who is more insane, the person tries to use the knob or the person put the knob on the cabinet and didn't think it's for decoration??

"Willy Denoyette [MVP]" <wi************ *@telenet.be> wrote in message
news:eA******** ******@TK2MSFTN GP10.phx.gbl...
Sorry what I meant was ""there is no documentation ... AND they don't

apply
here". If you need more info on GC safe points I'm afraid you'll have to look in the source code files of the CLR if you happen to have a Source

Code
License. Anyway, when your code calls GC.Collect it's always at a safe GC point, it's only when a GC is "induced" that it might get postponed when your code is not at a GC safe point.
What Billr proposed makes little sense in your case because your class

don't
own unmanaged resources, like DB connections, unmanaged memory OS handles etc..., it only consumes managed heap memory which is taken care of by
the
GC, there is no need to force collections by calling GC.Collect yourself. But if you really think you have to implement IDisposable, go ahead, but please tell us what you will do in your Dispose method.

I guess I'm more familiar with the process model than you might think.
The
asp.net hosting process recycles when it's Working Set exceeds the
memoryLimit% of total available memory, but the hosting process will try
to
survive first by forcing a full GC run, followed by an attempt to
reduce the
working set, then and ONLY when it's WS still exceeds the MemoryLimit%
it will recycle, else it simply continues to run.
In case the WS could not be reduced it's simply because an application
hosted in asp.net allocates too much memory or as a result of heap
fragmentation (take care when allocating many large objects (>85Kb)), or as
a result of a design error.
When it happens on a production system, it must be considered an

application
error , because the memoryLimit%, available system memory, number of

active
clients etc.. should have been defined during staging, when you
performed your load/stress testing and your workload modeling.

Willy.

"Zeng" <Ze******@hotma il.com> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
> I'm not sure on what you mean by "there is no documentation
> available...bec ause they don't apply here...". The existance of a
> document
> doesn't depend on what part of version of my code was posted. I
> appreciate
> your help looking into this for me, many people would just ignore posts > and
> move on even they know the answer or have some comments, but I don't

think
> we are going anywhere with it. My response was to BillR who proposes

that
> I
> should be implementing the IDisposable.
>
> It's the production environment, if the process get recycled, all my

cache
> in the memory will have to be reloaded when it goes back up. That
> would
> cause delay to the service that we want to provide. Sounds like you
> are
> not
> familiar with the processModel entry with attribute memoryLimit="60 " as > default, it's in the machine.config file. thanks!
>
>
> "Willy Denoyette [MVP]" <wi************ *@telenet.be> wrote in message
> news:O5******** *****@TK2MSFTNG P15.phx.gbl...
>> Again, you don't have to implement IDisposable when you don't deal
>> with
>> managed resources. What do you expect to do in your Dispose method?
>> And
>> No
>> there is no documentation available on Safe points, because they don't > apply
>> here (at least not in the code snip you've posted).
>> I'm also not clear on what you mean with recycling the asp.net

process,
> is
>> this something you intend to do or is it something that you are

expecting
> to
>> be done automatically, anyway before the asp.net process recycles,
>> all
>> application domains get unloaded, and this implies a GC run and a
> finalizer
>> run, so all objects (still referenced too) will be collected , but
>> even
> when
>> some objects aren't collected, all memory once allocated for the

process
>> will return to the OS when the process ends. So what are you afraid
>> of?
>>
>>
>> Willy.
>>
>> "Zeng" <Ze******@hotma il.com> wrote in message
>> news:uX******** ******@tk2msftn gp13.phx.gbl...
>> > Relying on IDisposable won't work easily in the multi-threading
> scenarios.
>> > Since the memory required for each object is big, I have put them on >> > static
>> > variable to share it among the servicing threads. Think of CMyClass is
>> > a
>> > spell-grammar-checker that helps looking up things and provide
> suggestions
>> > for correction for many users create their documents online. In
>> > this
>> > scenario, looks like there is the only choice
>> > --> Make CMyClass disposable and create managing component
(internal or
>> > external to the class) just to coordinate when and which objects
are > done
>> > just to call Dispose. This sounds like the intensive plumbing and
>> > error-prone approach that I was so used to with C++
>> >
>> > Conceptually, this is the drawback of a smart system, the programmer > knows
>> > what he/she needs to be done but can't change its behavior (which is > very
>> > very smart most of the time)
>> >
>> > By the way, where can I find a documentation about the safe-points? >> > Wouldn't that be better that there is a call to wait for the system to
> be
>> > done with collection and there is a safe point in that method? And
>> > is
>> > there
>> > a safe point in the component that checks for memory usage and

recycle
> the
>> > aspnet process when 60%(default) is reached?
>> >
>> >
>> >
>> > "billr" <bi***@discussi ons.microsoft.c om> wrote in message
>> > news:3B******** *************** ***********@mic rosoft.com...
>> >> 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 #22
That's strange, not too long ago Willy sounded so knowledgable about this
subject and almost like a salesman, now I haven't heard anything from him.
From this I can conclude:

1) Somehow Willy wouldn't dare to admit the truth that GC design and/or
implementation is messed up in this aspect. Hope he's not one of those
"bright" guys that Jon Shemitz referred to as responsible for GC
design/implementation.
2) GC is not releasing unused memory promptly and occasionally it is the
main cause for the process to get shutdown and recycled
2) GC is messing up another one. In the past I also found that that the LOH
(large object heap) gets fragmented gradually and the gap in between each
useful blocks might not ever get to be useful until the whole process gets
recycled (shutdown) because the total amount of used memory reaching max%.
The reason is GC never spends cpu cycles to compact it even before the
process recycles itself.
3) GC.Collect() has no useful purpose other than for decoration (marketing)
because calling it is bad - no one should ever call it, calling it doesn't
do what the name "Collect" suggests anyway. There is no reason for any app
to call it.

"Zeng" <Ze******@hotma il.com> wrote in message
news:ep******** ******@TK2MSFTN GP11.phx.gbl...
I'm asking you the same question as I have asked BillR:

Is it possible for my process to get recycled because it reaches memory
max% even though most of the memory counted as used is no longer needed by
my app and it is not freed because GC hasn't gotten a chance to do so
safely? If that's true, sounds to me that having a finalizer in my class or not would only *reduce* the chance of that occuring, but not *eliminate*, is that accessment accurate to you?

By the way, I hope I don't need to correct all my mis-understanding what the GC is meant for to raise that question.

"Willy Denoyette [MVP]" <wi************ *@telenet.be> wrote in message
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..
Seems like you have a fundamental mis-understanding on what the GC is meant
for and how it's actually performing.
The GC's task is, to collect the memory space occupied by non-reachable
objects and compact the generation it is actually collecting, so that a
contiguous free space remains in the heap to add new objects.
A full GC is a GC run that collects all generations, the current version

of
the CLR has 3 generational logical heaps plus a separate large object heap
(LOH), from code you can ask for a GC run by calling GC.Collect(n) where n indicates the generation to end with, a collection always starts with
generation 0.
GC.Collect() collects all generations plus the LOH, that's why it's called a
full collect.

However, it's NOT the task of the GC to bring down the heap size, that's the
task of the CLR memory manager , or the hosting process memory manager

(if any) in close cooperation with the OS.

Your code sample needs at least two GC.Collect() calls, that's because you have a Finalizer (destructor in C# parlance).
When an instance of a finalizable object gets instantiated, it's

registered
as finalizable.
When it is no longer rooted at the next GC run, it will be moved to the
finalizable queue, where it stays until after the finalizer has run, after which it's removed from the finalizer queue and it becomes eligible for
collection.
Note that it's possible that not all finalizables are immediately

finalized,
all depends on the load of the system and the time the finalizer thread
spends finalizing objects. The finalizer thread can be suspended before

all
finalizer have run, that's why we say at LEAST 2 GC runs, and why we

suggest
against destructors in C#.

Willy.

PS I suggest you start reading these (somewhat outdated) articles , before you start arguing about a subject you don't seem to fully understand.
http://msdn.microsoft.com/msdnmag/is...I/default.aspx
http://msdn.microsoft.com/msdnmag/is...2/default.aspx

"Zeng" <Ze******@hotma il.com> wrote in message
news:eq******** ******@TK2MSFTN GP14.phx.gbl...
From what I understand, Dispose method doesn't help freeing manage
resources, and that's consistent with what you are saying.

About the hosting process tries to do a full GC run before it recycles
based
on MemoryLimit%; I don't believe it at this point, if there is such

thing as
full GC and it's doing what we expect, then it should have been exposed so
we - developers - can call it when we need to bring down the heap size
immediately (of course we don't need this if full GC is actually possible privately to the framework, but I don't believe it). How many times
should
I try to call GC.Collect to free the dangling objects in my demo code?
And
if GC.Collect doesn't do what "Collect" means, what is its use? Purely
advertising?

Imagine somebody sell you a cabinet and there is knob on it, and he tells you that yes that's a knob but don't use it, you NEVER need or want to use it. If you actually never need to use it then it should be only for
decoration :) but that was only a speculation - and one day you
decide
to pull or turn it, and it doesn't do anything ... hahaha who is more insane, the person tries to use the knob or the person put the knob on the cabinet and didn't think it's for decoration??

"Willy Denoyette [MVP]" <wi************ *@telenet.be> wrote in message
news:eA******** ******@TK2MSFTN GP10.phx.gbl...
> Sorry what I meant was ""there is no documentation ... AND they don't
apply
> here". If you need more info on GC safe points I'm afraid you'll have to> look in the source code files of the CLR if you happen to have a
Source Code
> License. Anyway, when your code calls GC.Collect it's always at a safe
GC> point, it's only when a GC is "induced" that it might get postponed when> your code is not at a GC safe point.
> What Billr proposed makes little sense in your case because your
class don't
> own unmanaged resources, like DB connections, unmanaged memory OS
handles> etc..., it only consumes managed heap memory which is taken care of by> the
> GC, there is no need to force collections by calling GC.Collect yourself.> But if you really think you have to implement IDisposable, go ahead, but> please tell us what you will do in your Dispose method.
>
> I guess I'm more familiar with the process model than you might think.> The
> asp.net hosting process recycles when it's Working Set exceeds the
> memoryLimit% of total available memory, but the hosting process will try to
> survive first by forcing a full GC run, followed by an attempt to reduce the
> working set, then and ONLY when it's WS still exceeds the MemoryLimit% it
> will recycle, else it simply continues to run.
> In case the WS could not be reduced it's simply because an
application> hosted in asp.net allocates too much memory or as a result of heap
> fragmentation (take care when allocating many large objects (>85Kb)),
or as
> a result of a design error.
> When it happens on a production system, it must be considered an
application
> error , because the memoryLimit%, available system memory, number of
active
> clients etc.. should have been defined during staging, when you performed> your load/stress testing and your workload modeling.
>
> Willy.
>
> "Zeng" <Ze******@hotma il.com> wrote in message
> news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
> > I'm not sure on what you mean by "there is no documentation
> > available...bec ause they don't apply here...". The existance of a
> > document
> > doesn't depend on what part of version of my code was posted. I
> > appreciate
> > your help looking into this for me, many people would just ignore posts> > and
> > move on even they know the answer or have some comments, but I don't think
> > we are going anywhere with it. My response was to BillR who proposes that
> > I
> > should be implementing the IDisposable.
> >
> > It's the production environment, if the process get recycled, all my cache
> > in the memory will have to be reloaded when it goes back up. That
> > would
> > cause delay to the service that we want to provide. Sounds like you> > are
> > not
> > familiar with the processModel entry with attribute memoryLimit="60 " as
> > default, it's in the machine.config file. thanks!
> >
> >
> > "Willy Denoyette [MVP]" <wi************ *@telenet.be> wrote in
message> > news:O5******** *****@TK2MSFTNG P15.phx.gbl...
> >> Again, you don't have to implement IDisposable when you don't deal
> >> with
> >> managed resources. What do you expect to do in your Dispose method?> >> And
> >> No
> >> there is no documentation available on Safe points, because they
don't> > apply
> >> here (at least not in the code snip you've posted).
> >> I'm also not clear on what you mean with recycling the asp.net
process,
> > is
> >> this something you intend to do or is it something that you are
expecting
> > to
> >> be done automatically, anyway before the asp.net process recycles,> >> all
> >> application domains get unloaded, and this implies a GC run and a
> > finalizer
> >> run, so all objects (still referenced too) will be collected , but
> >> even
> > when
> >> some objects aren't collected, all memory once allocated for the
process
> >> will return to the OS when the process ends. So what are you afraid> >> of?
> >>
> >>
> >> Willy.
> >>
> >> "Zeng" <Ze******@hotma il.com> wrote in message
> >> news:uX******** ******@tk2msftn gp13.phx.gbl...
> >> > Relying on IDisposable won't work easily in the multi-threading
> > scenarios.
> >> > Since the memory required for each object is big, I have put them on
> >> > static
> >> > variable to share it among the servicing threads. Think of CMyClass is
> >> > a
> >> > spell-grammar-checker that helps looking up things and provide
> > suggestions
> >> > for correction for many users create their documents online. In
> >> > this
> >> > scenario, looks like there is the only choice
> >> > --> Make CMyClass disposable and create managing component (internal or
> >> > external to the class) just to coordinate when and which objects are> > done
> >> > just to call Dispose. This sounds like the intensive plumbing
and> >> > error-prone approach that I was so used to with C++
> >> >
> >> > Conceptually, this is the drawback of a smart system, the
programmer> > knows
> >> > what he/she needs to be done but can't change its behavior (which is
> > very
> >> > very smart most of the time)
> >> >
> >> > By the way, where can I find a documentation about the safe-points?> >> > Wouldn't that be better that there is a call to wait for the system to
> > be
> >> > done with collection and there is a safe point in that method?
And> >> > is
> >> > there
> >> > a safe point in the component that checks for memory usage and
recycle
> > the
> >> > aspnet process when 60%(default) is reached?
> >> >
> >> >
> >> >
> >> > "billr" <bi***@discussi ons.microsoft.c om> wrote in message
> >> > news:3B******** *************** ***********@mic rosoft.com...
> >> >> 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 #23

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

Similar topics

8
3417
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
2391
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
9706
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
9577
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
10325
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
10315
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
7615
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
6847
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
4295
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
3815
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2990
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.