Search code examples
c#asp.netlifecycle

Deallocation of resources when using static members


Consider situation when we have a class with couple of static methods that use one static object.

public class Person
{
    private static PresonActions actions = new PresonActions();

    public static void Walk()
    {
        actions.Walk();
    }
}

I know that the life cycle of static members in asp.net apps is equals to appdomain life cycle. So this means that the object is not destroyed and the resources are not deallocated until I'll restart the appdomain.

But if we will use a property to create an instance of class PresonActions each time something access it, will the object will be destroyed or not?

public class Person
{
    private static PresonActions actions { get { return new PresonActions(); } }

    public static void Walk()
    {
        actions.Walk();
    }
}

thanks.


Solution

  • Static variable continuouse allocation is an Evil. Keep an eye on your memory consuption, especially if you are talking about server side component (ASP.NET).

    To answer your question: GC collects when he can an object which none longer reference by anyone in application.

    Do not do this. It's very easy jump into memory problems with this approach and after spend hours to profile and find memory leaks.

    If you want to change an object content, write a function that updates object content, without creating a new instance of it.