Chapter 10 - Object lifetime

1. Class, object and reference

Recall that class is nothing more than a blueprint that describes how an instance of this type will look and feel in memory. And they are defined within a code file (.cs in C#).

After a class has been defined, you may allocate any number of objects using new keyword. Understand, however, that the new keyword returns a reference to the object on the heap, not the object itself. And if you declare the reference variable as a local variable in a method scrop, it is stored on the stack for further use in your application.

2. The basics of object lifetime

When you build c# application, .net runtime will take care of managed heap without your intervention.

The garbage collector will destory any object when it is no longer needed and unreachable by any part of your code base.

        static void MakeCar()
        {
            Car myCar = new Car ();
        }

Notice that Car reference myCar has been created directly within the method MakeCar() and has not been passed outside of the defining scope. Thus, once this method call completes, the myCar reference is no longer reachable, the object is now a candidate for garbage collection. However, you cannot guarantee that this object will be reclaimed from memory immediately after call has completed. It will be safely destroryed when CLR perform next garbage collection.

2.1 setting object reference to null

    static void MakeCar()
        {
            Car myCar = new Car ();
            myCar = null;
        }

When you assign object references to null, the compiler ensures the reference no longer points to any object. However, you must understand the process does not in any way force the garbage collector to fire up and remove the object from the heap.

3. Understanding object generations

When CLR is attempting to locate unreachable objects, it does not literally examine each and every object placed on the manged heap. It would obviously involve considerable time.

To help optimize the process, each object on the heap is assigned to a specific generation. The longer an object existed on the heap, the more likely it is to stay here.

Generation 0: new allocated object that has never been marked for collection

Generation 1: Identifies an object that has survived a garbage collection.

Generation 2: Identifies an object that has survived more than one sweep of the garbage collector.

The garbage collector will investigate all generation 0 first, then generation 1 and 2.

The bottom line is that by assigning a generational value to objects on the heap, newer objects will be removed quickly.

4. System.GC 

The mscorlib.dll assemlby provides a class type named System.GC that allows you to interact with garbage collector. Do be very aware that you will seldom need to make use of this class directly in your code.

4.1 Forcing a garbage collection

There are two common situations where you might consider interacting with the collection process:

(1) your application is about to enter into a block of code that you don‘t want interrupted by a possible garbage collection.

(2) your application has just finished allocating an extremely large number of objects and you want to remove as much of the acquired memory as soon as possible

You could trigger a garbage collection as follows:

        public static void Main (string[] args)
        {
            //force garbage collection
            GC.Collect();
            GC.WaitForPendingFinalizers ();
        }

When you manually force a garbase collection, you should always make a call to GC.WaitForPendingFinalizers(). With the approach, you can rest assured that all finalizable objects have had a change to perform any necessary cleanup before your program continues. Under the hood, it will suspend the calling thread during the collection process.

GC.Collect() can also be supplied a numerical value that identifies the oldest generation on which a garbage collection will be performed.

public static void Main (string[] args)
        {
            //only investigate generation 0 objects
            GC.Collect(0);
            GC.WaitForPendingFinalizers ();
        }

Also, the Collect() method can also be passed in a value of the GCCollectionMode enumeration as a second parameter.

        public static void Main (string[] args)
        {
            //force it immediately
            GC.Collect(0, GCCollectionMode.Forced);
            GC.WaitForPendingFinalizers ();
        }

5. Building Finalizable Objects

In .net framework, System.Object class defines a virtual method named Finalize() which is used to perform any necessary clearnup logic for your type. The majority of your c# classes will not require any explicit cleanup logic or a custom finalizer. The only time you would need to design a class that can clean up is when you are using unmanaged resources such as using PInvoke or COM objects.

6. Disposable objects

As an alternative to overriding Finalize(), you class could implment the IDisposable inteface.

    public interface IDisposable
    {
        void Dispose();
    }

When you do implment the IDisposable, the object user manually calls dispose before allowing the object reference to drop out of sceop. In this way, an object can perform immediate cleanup without waiting for garbage collector or finalizarion queue.

        public static void Main (string[] args)
        {
            FileStream fs = new FileStream ("test.txt", FileMode.OpenOrCreate);

            fs.Close ();  //both method do the same thing
            fs.Dispose ();
        }

6.1 C# using keyword

When you are handling a managed object that implent IDisposable intefarce, it is common to make use of stucture of exception-handling to ensure Dispose() is called.

        public static void Main (string[] args)
        {
            FileStream fs = new FileStream ("test.txt", FileMode.OpenOrCreate);
            try{
                //use of fs
            }
            finally {
                fs.Close ();  //both method do the same thing
                fs.Dispose ();
            }
        }

And to achieve the same resule in a much less obtrusive manner, C# support using keyword.

        public static void Main (string[] args)
        {
            //dispose is called automatically
            using (FileStream fs = new FileStream ("test.txt", FileMode.OpenOrCreate)) {

            }
        }

In fact, at the backgourd, the compiler translate using statement to a proper try, catch and the calling dispose() methods.

时间: 2024-10-12 02:57:56

Chapter 10 - Object lifetime的相关文章

Cpp Chapter 10: Objects and Classes Part2

10.2.4 Using classes Following exapmle uses the class definition and implementation written in previous files: // usestok0.cpp -- the client program // compiler with stock00.cpp #include <iostream> #include "stock00.h" int main() { Stock s

零元学Expression Blend 4 - Chapter 10 用实例了解布局容器系列-「StackPanel」

原文:零元学Expression Blend 4 - Chapter 10 用实例了解布局容器系列-「StackPanel」 本系列将教大家以实做案例认识Blend 4 的布局容器,此章介绍的布局容器是Blend 4 里的乖宝宝-「StackPanel」:及加码赠送「ScrollViewer」的运用. 本系列将教大家以实做案例认识Blend 4 的布局容器,此章介绍的布局容器是Blend 4 里的乖宝宝-「StackPanel」:及加码赠送「ScrollViewer」的运用. 就是要让不会的新手

Python Chapter 10: 列表 Part3

10.10 查找列表 )线性查找 线性查找顺序地将关键字key与列表中的每一个元素进行比较,直到找到某个匹配元素时返回其下标,亦或在找不到时返回-1.代码如下: # The function for finding a key in a list def linearSearch(lst, key): for i in range(len(lst)): if lst[i] == key: return i return -1 若关键字存在,线性查找在找到关键字前平均需要查找一半的元素,其运行时间

Thinking in Java from Chapter 10

From Thinking in Java 4th Edition 内部类 public class Parcel1 { class Contents { private int i = 11; public int value { return i;} } class Destination { private String label; Destination(String whereTo) { label = whereTo; } String readLabel() { return l

C++ chapter 10——模板

**模板的概念 函数模板 类模板 名空间** 一.模板的概念 C++的模板提供对逻辑结构相同的数据对象通用行为的定义.模板运算对象的类型不是实际的数据类型,而是一种参数化的类型. 一个带类型参数的函数称为函数模板,一个带类型参数的类称为类模板. 二.函数模板 1.函数模板的概念 函数模板的基本原理是通过数据类型的参数化,将一组算法相同但所处理数据类型不同的重载函数凝练成一个函数模板.编译时,再由编译器按照函数模板自动生成针对不同数据类型的重载函数定义代码. 使用函数模板.对于函数模板,数据类型本

Chapter 10 Networking/JSON Services

<1>JSON Service In the previous section, you learned how to consume XML web services by using HTTP to connect to the web server and then obtain the results in XML. You also learned how to use DOM to parse the result of the XML document. However, man

BDA chapter 10

numerical integration, 数值积分.numerical integration refers to methods in which the integral over continuous function is evaluated by computing the value of the function at finite number of points. Numerical integration methods can be divided to simulat

Head first java chapter 10 数字与静态

注意,先输出静态定义,然后运行main,输出"in main",然后statictests继承自staticsuper,所以先实现staticsuper,然后再实现statictests.

数据库 chapter 10 数据库恢复技术

第十章 数据库恢复技术 介绍事务的基本概念和事务的性质,讲解数据库系统遇到故障后进行恢复技术和方法. 事务是一系列的数据库操作,是数据库应用程序的基本逻辑单元,是一个不可分割的工作单位. 事务和程序是两个概念,一般来说,一个程序里面包含多个事务. 事务处理技术主要包括数据库恢复技术和并发控制技术. 事务具有四个特性:原子性(Atomicity).一致性(Consistency).隔离性(Isolation)和持续性(Durability),这四个特性简称为ACID特性. 原子性:事务时数据库的逻