Re: A question about life cycle of an object.

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



Xiuming wrote:

Hi Barry.

I tested it again and found that those objects were in gen2 indeed, as
what you had said. After calling GC.Collect(2), memory used by the
objects was released.
Those objects still exist and will last for very long time, even no
other live objects reference them!
This leads to another question: Is it possible to regain the access to
those objects?

If the objects (or in particular, the root object) has a finalizer, then
you can reassign the root into the global object graph and get it back
that way. However, finalizers make objects a bit more expensive to
allocate, and also cost resources because the GC needs to do more work
to keep track of them. It's better not to throw away an object graph if
you are likely to need it to live for a long time with only intermittent
timespans where it is eligible to become garbage.

Try this app for resurrection:

---8<---
using System;

class Root
{
public static volatile Root Zombie;

public Item Head;
int LifeCount = 2;

~Root()
{
if (--LifeCount > 0)
{
Console.WriteLine("Resurrecting root");
Zombie = this;
}
}
}

class Item
{
public Item Next;
}

class App
{
static void Main()
{
Root root = new Root() { Head = MakeList(10) };
Console.WriteLine("Root generation: {0}",
GC.GetGeneration(root));
GC.Collect(2);
Console.WriteLine("Root generation: {0}",
GC.GetGeneration(root));
root = null;
GC.Collect(2);
GC.WaitForPendingFinalizers();
root = Root.Zombie;
Root.Zombie = null;
Console.WriteLine("Root generation: {0}",
GC.GetGeneration(root));
Console.WriteLine("List length: {0}", ListLength(root.Head));
}

static int ListLength(Item item)
{
if (item == null)
return 0;
return 1 + ListLength(item.Next);
}

static Item MakeList(int count)
{
Item result = null;

while (count > 0)
{
--count;
result = new Item() { Next = result };
}

return result;
}
}
--->8---


-- Barry

--
http://barrkel.blogspot.com/
.



Relevant Pages