65.9K
CodeProject is changing. Read more.
Home

Track Object Finalization

starIconstarIconstarIconstarIconstarIcon

5.00/5 (5 votes)

Dec 31, 2010

CPOL
viewsIcon

21466

Make sure your objects are garbage collected

Sometimes, it's useful to detect when an object is garbage collected.

Garbage collection happens in a separate thread, and if you want to display some information about this, in a Windows Forms GUI, you need to use BeginInvoke and not Invoke or your application will "freeze".

Invoke will not be executed during garbage collection.

#if DEBUG
  private static long objectsDestroyedCounter = 0;
  ~Entity( )
  {
    objectsDestroyedCounter++;
    if( (objectsDestroyedCounter % 10000) == 0)
    {
      LogDebug(string.Format("{0} objects dropped.",objectsDestroyedCounter) );
    }
  }

  private static void LogDebug(string s)
  {
    MainForm.LogString(s);
  }

#endif

Execution of the code actually displaying the information is deferred until after the garbage collector has finished.

class MainForm : Form
{
  private static MainForm instance;
  
  public MainForm()
  {
  ....
    instance = this;
  }

  public static MainForm Instance
  {
    get
    {
      return instance; 
    }
  }

  public static void LogString(string s)
  {
    MainForm mainForm = Instance;
    if( mainForm != null )
    {
      Instance_MessageLogged(mainForm,s);
    }
  }

delegate void Instance_MessageLoggedDelegate(object sender, string message);

  void Instance_MessageLogged(object sender, string message)
    {
      if (InvokeRequired)
      {
        BeginInvoke(new Instance_MessageLoggedDelegate (Instance_MessageLogged), 
                    new object[] { sender, message });
      }
      else
      {
        // Executed on the GUI thread after GC has completed
        messagesTextBox.AppendText(message);
      }
    }
}

I hope that it might be useful.