Simple Stack & Heap Allocation With Garbage Collection

Destructors

Here is another simple program that shows how Garbage Collection works in C# .NET. What I’m doing is creating a couple of objects, showing how GC memory there is upon creation, destroying the object so it’s flagged for GC collection, and showing the GC memory after the object has been destroyed. Click more to see the source code.

Destructors Class:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Destructors
{
    public partial class Destructors : Form
    {
        private Bag _bag = null;
        private MyBag _myBag = null;
        
        public Destructors()
        {
            InitializeComponent();
        }

        private void createButton_Click(object sender, EventArgs e)
        {
            //Checking to see if more than one object can be created.
            if (_bag != null || _myBag != null)
            {
                Console.WriteLine("Sorry, these objects have been created already.");
            }
            
            //Only create a single Bag.
            if (_bag == null)
            {
                //Create a new Bag instance.
                _bag = new Bag();
                
                //Create a variable that requires a large block of heap memory.
                byte[] byteArray = new byte[100000];
                for (int i = 0; i < byteArray.Length; i++)
                {
                    byteArray[i] = 1;
                }

                //Add the variable to our bag.
                _bag.Items.Add(byteArray);
                
                //Displaying the results.
                outputListBox.Items.Add("Bag Create: GC Memory(bytes): " + GC.GetTotalMemory(true).ToString());
                outputListBox.Items.Add("");
            }

            //Working with the MyBag class.
            if (_myBag == null)
            {
                //Creating a new object.
                _myBag = new MyBag();

                //Adding the strings.
                _myBag.stringOne = "This is a test for stringOne.";
                _myBag.stringTwo = "This is a test for stringTwo.";
                _myBag.stringThree = "This is a test for stringThree.";

                //Displaying the GC results.
                outputListBox.Items.Add("MyBag Create: GC Memory(bytes)" + GC.GetTotalMemory(true).ToString());
                outputListBox.Items.Add("");    //Line seperator.
            }
        }

        private void destroyButton_Click(object sender, EventArgs e)
        {
            //Checking to see if the object is in fact destroyed.
            if (_bag == null || _myBag == null)
            {
                Console.WriteLine("Sorry these objects have been destroyed.");
            }
            
            //Make sure a Bag has been created.
            if (_bag != null)
            {
                //Remove the reference to our Bag allocated memory.
                _bag = null;

                //Displaying the results.
                outputListBox.Items.Add("Bag Destroy: GC Memory(bytes): " + GC.GetTotalMemory(true).ToString());
                outputListBox.Items.Add("");
            }

            if (_myBag != null)
            {
                //Removing the string data.
                _myBag = null;

                //Displaying the GC data.
                outputListBox.Items.Add("MyBag Destroy: GC Memory(bytes)" + GC.GetTotalMemory(true).ToString());
                outputListBox.Items.Add("");    //Line seperator.
            }
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Destructors_Shown(object sender, EventArgs e)
        {
            //Getting the memory amount on program load.
            outputListBox.Items.Add("Program start: GC Memory (bytes): " + GC.GetTotalMemory(true).ToString());
            outputListBox.Items.Add("");
        }
    }
}

MyBag Class:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Destructors
{
    class MyBag
    {
        //Setting up a stopwatch for timing.
        private Stopwatch _stopWatch = new Stopwatch();

        public string stringOne { get; set; }
        public string stringTwo { get; set; }
        public string stringThree { get; set; }

        //MyBag constructor method.
        public MyBag()
        {
            _stopWatch.Start();
            Console.WriteLine("MyBag class stopwatch has been started.");
        }

        //MyBag Destructor method.
        ~MyBag()
        {
            _stopWatch.Stop();
            Console.WriteLine("MyBag class stopwatch has been stopped. Objects existed for " +
                _stopWatch.ElapsedMilliseconds / 1000 + " seconds.");
        }
    }
}

Bag Class:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Destructors
{
    class Bag
    {
        public List Items { get; set; }

        private Stopwatch _stopWatch = new Stopwatch();

        //Constructor method
        public Bag()
        {
            _stopWatch.Start();
            Console.WriteLine("Bag constructor, start stop watch");
            Items = new List();
        }

        //Destructor method.
        ~Bag()
        {
            _stopWatch.Stop();
            Console.WriteLine("Bag destructor, stop watch stopped, object existed for " +
                _stopWatch.ElapsedMilliseconds / 1000 + " seconds");
        }
    }
}

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s