Friday, November 29, 2013

Try out- GC.Collect executed in Separate Thread

Garbage collection works in a separate thread. Want to check this out.

 

Execute the following code in a Console Project.

 

using System;
using System.Threading;


 

namespace Demo {
    class Program {
        public static void Main(string[] args) {
            Log("Calling Test");
            Test();
            //GC.Collect(0, GCCollectionMode.Forced);
            Thread.Sleep(2000);
            Log("Called Test");
        }

        public static void Test() {
            Person p = new Person();
            p = null;

        }

        public static void Log(string s) {
            Console.WriteLine("In Thread {0}({1})- {2}", Thread.CurrentThread.Name, Thread.CurrentThread.ManagedThreadId, s);
            Thread.Sleep(2000);
        }
    }

    public class Person {
        public Person() {
            Program.Log("Person");
        }
        ~Person() {
            Program.Log("~Person");
        }
    }
}

 

You can expect an output showing some logs in a main thread and the destructor log in a separate thread. Garbage collection is done automatically while the program exists as it a small program and does not usually do a collection in between the program.

To check the forced collection, uncomment the following line in main.

//GC.Collect(0, GCCollectionMode.Forced);