垃圾收集器静态字段 [英] Garbage Collector Static Fileds

查看:94
本文介绍了垃圾收集器静态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果我有一个带有某些静态变量的类,如下所示:

Hi,

If i have a class with some statics filed like below:

class Test{

public static SomeotherClass _someotherclassObj=new SomeotherClass();

//other members and method..

}



如果我有100个Test类的实例,这些实例将被Garbage Collector标记为可达(由于静态成员),并将一直保留到应用程序结束.

谢谢!!
Rahul



If i have 100 instances of class Test, will those instances will be marked reachable by Garbage Collector (because of static member) and will remain till application ends.

Thanks!!
Rahul

推荐答案

在将静态对象设置为NULL之前,它们始终被标记为未进行垃圾回收. 这是一篇很好的文章,对本主题有更多的解释:
http://msdn.microsoft.com/en-us/magazine/bb985010.aspx [ ^ ]
Static objects are always marked to be NOT garbage collected until they are set to NULL.
Here is a nice article that explains a bit more about the topic:
http://msdn.microsoft.com/en-us/magazine/bb985010.aspx[^]


仅当相关AppDomain被垃圾回收时,静态变量引用的对象才会被垃圾回收.在客户端应用程序中,通常只有一个AppDomain在整个过程中一直存在. (一个例外是,当应用程序使用插件体系结构时-不同的插件可能会加载到不同的AppDomain中,而AppDomain可能会在以后卸载.)

在ASP.NET中,"AppDomain回收"周期性地发生(由于各种原因)-发生这种情况时,该AppDomain中的静态变量将不再充当GC的根,因此不会阻止对象被垃圾回收.

但是,如果您担心某个对象仍在通过静态变量对其进行引用的同时被垃圾回收,则可以放轻松.虽然可以访问该对象,但不会对其进行垃圾回收.
Objects referenced by static variables will only be garbage collected when the relevant AppDomain is garbage collected. In client applications, there''s often just a single AppDomain which lives for the duration of the process. (An exception is when the application uses a plug-in architecture - different plug-ins may be loaded in different AppDomains and the AppDomain may be unloaded later.)

In ASP.NET, "AppDomain recycling" happens periodically (for various reasons) - when this occurs, and the static variables within that AppDomain will no longer act as GC roots, and thus won''t prevent objects being garbage collected.

If you were worried about an object being garbage collected while you still had a reference to it via a static variable, though, you can relax. While you can access the object, it won''t be garbage collected.


这篇关于垃圾收集器静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆