Home > .Net, GC > When and how to use GC.KeepAlive in .Net

When and how to use GC.KeepAlive in .Net

Let’s look on the following C# code example (ignore the correctness of the code and its logic)

    /// <summary>
    /// Indicates any service Logger for example
    /// </summary>
    class MyService
    {
        public MyService(string fileName)
        {
            //Do some initializations
        }

        public static void DoSomething()
        {
            //some calculations, or logs creation
        }
    }
    //*************************************************
    /// <summary>
    /// Usage example class 
    /// </summary>
    class MyLogic
    {
        public void Foo()
        {
            //cals static method of the initialized service
            MyService.DoSomething();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //Create our service 
            MyService myService = new MyService("temp.txt");
            //Wait here for user
            Console.ReadLine();
        }
    }


So far so good, but you are asking – where the problem??

Initializing MyService object in Main method and all other code uses the same instance static method.
Important to understand that there is only one reference that holds MyService myService instance object. In Debug version application will run as you expecting – usual. All usages of MyService will succeed however Release version of this application as a result of GC optimizations (that I can’t say exactly when and what algorithm is running). GC mechanism will realize that there is only one reference to the object; as a result of such conclusion GC will collect our object, next access to myService object will crash the application.
Of cause the object could be everything – some Manager that responsible for communication or anything else ….
The solution:
Add function call GC.KeepAlive(myService), as it described in following C# example

static void Main(string[] args)
        {
            //Create our service 
            MyService myService = new MyService("temp.txt");
            //Wait here for user
            Console.ReadLine();

            GC.KeepAlive(myService);

        }

By adding this command to the GC we are guarantee that our myService object will survive all Main function life time. Behind the scenes CLR add dummy reference to our object. Another solution is to add static member that will hold the object.
This post came after real live application bugs that caused us lots of debugging houers while trying to understand why Process suddenly crashes.

Categories: .Net, GC Tags: ,
  1. September 6th, 2014 at 18:36 | #1

    This website was… how do you say it? Relevant!! Fihally I’ve found
    someting that helped me. Appreciate it!

  1. No trackbacks yet.