什么是.NET对象生命周期? [英] What is the .NET object life cycle?

查看:96
本文介绍了什么是.NET对象生命周期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET中对象的对象生命周期是什么?

What is the object life cycle for an object in .NET?

据我了解,它是:


  1. 对象已创建-调用的构造函数(如果存在)

  2. 方法/属性/使用的字段

  3. 对象已销毁-处理被调用(如果存在的话)

  4. 在某些时候由GC调用的析构函数

  1. Object created - constructor called (if one exists)
  2. Methods/Properties/Fields used
  3. Object destroyed - Dispose called (if one exists)
  4. Destructor called by GC at some point


推荐答案

处置不会自动被调用;您需要调用它,或使用using块,例如。

Dispose doesn't get called automatically; you need to call it, or use a using block, eg.

using(Stream s = File.OpenRead(@"c:\temp\somefile.txt"))
    // Do something with s

终结器仅在存在时才由GC调用。拥有终结器可以分两步收集您的课程;首先将对象放入终结器队列中,然后调用终结器并收集对象。没有终结器的对象将被直接收集。

The finalizer only gets called by the GC if it exists. Having a finalizer causes your class to be collected in 2 steps; first the object is put in the finalizer queue, then the finalizer is called and the object is collected. Objects without finalizers are directly collected.

准则是Dispose摆脱了托管和非托管资源,终结器仅清理了非托管资源。当Dispose方法释放了非托管资源后,它可以调用GC.SuppressFinalize,以免将对象放置很长时间以放置在终结器队列中。有关正确的处置模式示例,请参见 MSDN

The guideline is that Dispose gets rid of managed and unmanaged resources, and the finalizer only cleans up unmanaged resources. When the Dispose method has freed the unmanaged resources it can call GC.SuppressFinalize to avoid the object from living long to be put on the finalizer queue. See MSDN for a correct sample of the dispose pattern.

这篇关于什么是.NET对象生命周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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