开发者

Deallocation of resources when using static members

开发者 https://www.devze.com 2023-04-03 00:06 出处:网络
Consider situation when we have a class with couple of static methods that use one static object. public class Person

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 resou开发者_如何学Pythonrces 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.


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.


In your second code example, the garbage collector will destroy the object some time after the call to actions.Walk(). The garbage collector does this in a non-deterministic fashion, i.e. you cannot determine when it will perform this operation.

If your type is using resources which you want to dispose of deterministically, then the type should implement IDisposable and it's implementation of the Dispose method should perform the disposal of those resources.

Consuming code can then either call this method directly or use a using block to dispose of the object which in turn disposes of it's resources.

e.g.:-

public class PresonActions : IDisposable
{
    ...
    public void Dispose()
    {
        ...
    }
}

public class Person
{
    public static void Walk()
    {
        using(var actions = new PresonActions())
        {
            actions.Walk();
        }
    }
}

Note that, since you are not using the instance for more than one method call, there is no point creating it in a static property. It can be created it within the method, which allows use of a using block.

0

精彩评论

暂无评论...
验证码 换一张
取 消