开发者

When will an object declared in a static class get garbage collected?

 public static class stClass
{
    static Class1 obj = new Class1();

    public static int returnSomething()
    {
        return 0;
    }
}

When will the Class1 instance obj in stClass get garbage collected, if i am calling the static function stClass.returnSomet开发者_开发技巧hing() in some other non static class ?

Note: Class1 is not static


Never, as obj does not implement IDisposable.

If you mean when will obj get garbage collected then the answer is still never - static fields are never garbage collected and so the object that obj references will only become eligible for garbage collection if you set obj to be null (or some other object) and have no other references to that object:

obj = null;

(or if your app domain is unloaded / the process ended)


It will never get disposed as it doesn't implement IDisposable. However it will get garbage collected. This will happen when you exit your application or you destroy the AppDomain that the class was created in.


If Class1 implements the IDisposable interface & has a finalizer, the runtime will attempt to call the finalizer when the appdomain is unloaded*. If Class1 follows the dispose pattern properly, the finalizer should call dispose(false). This would be the correct time to unload any unmanaged resources being used by the Class1 instance.

However, when dealing with an object that uses unmanaged resources, you should strive to take more control over the object lifecycle rather than just letting the finalizer run when the appdomain shuts down.

*Even the finalizer is not guaranteed to be called when the app shuts down..

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜