tags:

views:

71

answers:

4

We have an event class which has a reference of a MsgBody class:

public class StatusEvent
{
   MsgBody msgBody;
   public StatusEvent(MsgBody body)
   {
       msgBody = body;
   }
....
}

public class MsgBody
{
   string s1;
   string s2;
.....

}

MsgBody class is ONLY used by StatusEvent. No other place a MsgBody is refered. When a StatusEvent instance is created, a MsgBody instance will be created. When a StatusEvent object is ready for cleanup, a MsgBody object will be safe to be cleanup.

But the result is the MsgBody cleanup is way behind the StatusEvent. From one profiler result, I found there ware only 43 Live instances of StatusEvent but there were 9,940 instances of MsgBody!

Is there a way to link them together and make GC cleanup MsgBody when it wipe StatusEvent away?

thanks,

+1  A: 

If you want deterministic release of resources, StatusEvent needs to implement IDisposable. In the IDisposable.Dispose method implementation, you can release all the resources held. In your case you can put the statement msgBody = null; to your code.

Are you sure there is no other place where msgBody is being stored?

Chetan
Yes, I am sure there is no other place hold the msgBody.
5YrsLaterDBA
It is not necessary to implement IDisposable to clear a reference. Setting the reference to null may make the inner reference eligible for GC sooner than the owner (it might already be eligible even before it was set to null, actually), but it will also be eligible as soon as the parent object is no longer referenced.
Dan Bryant
A: 

Normally the GC should automatically free the memory as soon as the memory is needed anywhere else. But if you want to speed this up, you can call the following to free memory immidiately:

http://msdn.microsoft.com/en-us/library/system.gc.collect.aspx

Chris
Doing this will probably have adverse effects on the execution and is not recommended.
Chris Dunaway
Sometimes it is better to call system.gc.collect manually if you know that now is enough free time to collect, but in future you will have a lot of work to do so the GC could take cpu time and memory bandwidth you need.
Chris
No, it's not better. GC.Collect is in the framework for entirely different reason namely allowing libraries to clean up large resources before the GC gets "trained". If you do this because "you know that now is enough free time" you will just disrupt the GC training and it will be less effective.
Stilgar
Thank you for this info! It seems that I made wrong assumptions in history. Do you have further information material regarding GC "training"?
Chris
A: 

If the MsgBody does not have any expensive resource access, then the GC will take care once the object is out of scope. Aditionally you can set msgBody=null;.

Siva Gopal
A: 

If you don't call GC.Collect(), so it would totally depend on GC. I don't think there's the way to instruct GC in the manner you want.

tia