Re: Prematurely garbage collection
- From: "Gaurav Khanna [MSFT]" <gkhanna@xxxxxxxxxxxxxxxxxxxx>
- Date: Sun, 20 May 2007 01:18:54 -0700
If an object has a reference available from an application root, it will not be collected. In the example below, when Invoke is being executed, the reference of the instance is available with app root - so the object is not collected until there are no more pending references. Executing the example given by Jon below on my machine gave the following output:
Start of method
Called GC
End of method
Finalizer
To better illustrate this point, see the attached file that contains a modified version of the example below. As expected, the output is:
Start of method
Finalizer of 1
Called GC
End of method
Finalizer of 2
--
Thanks!
Gaurav
WinToolZone - http://www.wintoolzone.com/
Inside and Out - http://www.wintoolzone.com/blog/
The information in this post is provided "AS IS" with no warranties, and confers no rights.
"Jon Skeet [C# MVP]" <skeet@xxxxxxxxx> wrote in message news:MPG.20b8326cc9c8494d128@xxxxxxxxxxxxxxxxxxxxxxx
Chitrsen <Chitrsen@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:using System;1. GC will not recollect the memory assigned to running object.
Yes it can.
2. if you open IL of code '(new Instance()).Invoke();', you can see clr
gives a random generated name for this instance. use ildasm.exe to verify it.
It can still be garbage collected before Invoke() has finished
executing. Here's an example:
using System;
using System.Threading;
class Test
{
~Test()
{
Console.WriteLine ("Finalizer");
}
void Invoke()
{
Console.WriteLine ("Start of method");
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine ("Called GC");
Thread.Sleep(1000);
Console.WriteLine ("End of method");
}
static void Main()
{
new Test().Invoke();
}
}
On my box that prints:
Start of method
Finalizer
Called GC
End of method
--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
using System.Threading;
class Test
{
internal int m_index;
public Test(int index)
{
m_index = index;
}
~Test()
{
Console.WriteLine("Finalizer of {0}", m_index);
}
void Invoke()
{
Console.WriteLine("Start of method");
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("Called GC");
Thread.Sleep(1000);
Console.WriteLine("End of method");
}
static void Main()
{
new Test(1);
new Test(2).Invoke();
}
}
- Follow-Ups:
- Re: Prematurely garbage collection
- From: Jon Skeet [C# MVP]
- Re: Prematurely garbage collection
- References:
- RE: Prematurely garbage collection
- From: Jon Skeet [C# MVP]
- RE: Prematurely garbage collection
- Prev by Date: Re: Can't load CLR on TabletPC with VSTO2003 apps
- Next by Date: Re: how to deal with valueless callstack when an exception finally propagated from unmanaged code to managed code?
- Previous by thread: Re: Prematurely garbage collection
- Next by thread: Re: Prematurely garbage collection
- Index(es):
Relevant Pages
|