Tải bản đầy đủ (.pdf) (62 trang)

Tài liệu Module 9: Memory and Resource Management ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (952.02 KB, 62 trang )









Contents
Overview 1
Memory Management Basics 2
Non-Memory Resource Management 12
Implicit Resource Management 13
Explicit Resource Management 26
Optimizing Garbage Collection 36
Lab 9: Memory and Resource Management 48
Review 55

Module 9: Memory and
Resource Management


Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.



Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

 2001-2002 Microsoft Corporation. All rights reserved.

Microsoft, ActiveX, BizTalk, IntelliMirror, Jscript, MSDN, MS-DOS, MSN, PowerPoint,
Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, Windows, Windows Media, and
Window NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.



Module 9: Memory and Resource Management iii


Instructor Notes
After completing this module, students will be able to:
!
Describe how garbage collection manages object memory.
!
Implicitly manage non-memory resources by using a destructor’s finalize
code.
!
Explicitly manage non-memory resources by using client-controlled

deterministic release of resources.
!
Write code by using the temporary resource usage design pattern.
!
Programmatically control the behavior of the garbage collection.
!
Describe advanced garbage collection features.

Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.
Required Materials
To teach this module, you need the Microsoft
®
PowerPoint
®
file 2349B_09.ppt.
Preparation Tasks
To prepare for this module, you should:
!
Read all of the materials for this module.
!
Review the animation.
!
Practice the demonstrations.
!
Complete the lab.

Presentation:
125 Minutes


Lab:
60 Minutes
iv Module 9: Memory and Resource Management


Demonstrations
This section provides demonstration procedures that will not fit in the margin
notes or are not appropriate for the student notes.
The code for each of the following demonstrations is contained in one project
and is located in <install folder>\Democode\Mod09\
GARBAGE COLLECTION. In addition, the code for the individual
demonstrations is provided in the student notes.
Use the debugger to step through the code while you point out features and ask
students what they think will happen next.
Finalization
In this demonstration, you will show students how garbage collection handles
finalization and resurrection. In this demonstration, run the Introduction and
ResurrectionDemo methods.
The IDisposable Interface
In this demonstration, you will show students how to perform explicit resource
management by using the IDisposable interface. In this demonstration, run the
DisposeDemo method.
Weak References
In this demonstration, you will show students how garbage collection handles
weak references. In this demonstration, run the WeakRefDemo method.
Generations
In this demonstration, you will show students how garbage collection handles
generations. In this demonstration, run the GenerationDemo method.
Multimedia

This section lists the multimedia items that are part of this module. Instructions
for launching and playing the multimedia are included with the relevant slides.
Simple Garbage Collection
This animation will show students the Microsoft .NET Framework common
language runtime’s garbage collection process without finalization.
Garbage Collection
This animation will show students the .NET Framework common language
runtime garbage collection process, including finalization.
Module 9: Memory and Resource Management v


Module Strategy
Use the following strategy to present this module:
!
Memory Management Basics
Students in your classes will probably use different approaches to memory
management. Begin with a brief review of different memory management
techniques that you or the students may have learned from experience.
Because students will need to adapt their programming practices to the
automatic memory management that is provided by the common language
runtime, it is important to mention other memory management techniques.
Compare and contrast manual memory management with the automatic
memory management that is provided by the common language runtime.
Outline the simple garbage collection process without the finalization details
and use the Simple Garbage Collection animation to help the students
understand the concept of the garbage collection process more easily.
Instructions for running the animations in this module are included in
Instructor Margin Notes.
!
Non-Memory Resource Management

This topic is an introduction to handling non-memory resources implicitly
and explicitly. Tell students that the next two sections cover these areas in
detail. You should not spend much time on this slide.
!
Implicit Resource Management
Introduce the finalization phase of the garbage collection process.
Emphasize that in C#, a destructor must be used for the finalization code.
The second animation, Garbage Collection, is more complex than the first.
It shows the garbage collection process with the finalization details.
Spend time discussing the drawbacks that are associated with finalization
and what to do if finalization is required. Show students how to deal with an
object that has been resurrected.
Use the Finalization demonstration to highlight how garbage collection
deals with finalization and resurrection.
!
Explicit Resource Management
Show students how to perform explicit resource management by using the
IDisposable interface and Dispose method.
Discuss the temporary resource usage design pattern as an example of how
to allocate resources for temporary use.
!
Optimizing Garbage Collection
Use the demonstrations that are provided to show how to optimize garbage
collection through weak references and generations.
In addition to discussing the programmatic optimizations that can be made
to the garbage collection process, briefly mention the use of performance
counters to monitor memory activity and the use of a multiprocessor system
to scale applications where there are garbage collection bottlenecks.



Module 9: Memory and Resource Management 1


Overview
!
Memory Management Basics
!
Non-Memory Resource Management
!
Implicit Resource Management
!
Explicit Resource Management
!
Optimizing Garbage Collection

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Objects in the Microsoft
®
.NET Framework use memory resources and may use
other resources, such as file handles. For software to run properly, these
resources must be well managed. In other words, they must be properly
allocated and released.
After completing this module, you will be able to:
!
Describe how garbage collection manages object memory.
!

Implicitly manage non-memory resources by using a destructor’s finalize
code.
!
Explicitly manage non-memory resources by using client-controlled
deterministic release of resources.
!
Write code by using the temporary resource usage design pattern.
!
Programmatically control the behavior of the garbage collection.
!
Describe advanced garbage collection features.

Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
Objects in the Microsoft
.NET Framework use
memory resources and may
use other resources, such
as file handles. For software
to run properly, these
resources must be well
managed.
2 Module 9: Memory and Resource Management


"
""

"

Memory Management Basics
!
Developer Backgrounds
!
Manual vs. Automatic Memory Management
!
Memory Management of .NET Framework Types
!
Simple Garbage Collection

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
A major feature of the .NET Framework common language runtime is that the
runtime automatically handles the allocation and release of an object’s memory
resources. In most cases, automatic memory management enhances code quality
and developer productivity without negatively impacting expressiveness or
performance.
Understanding how the .NET Framework facilitates resource management is
essential for writing correct and efficient code.
In this section, you will learn about memory management in the .NET
Framework, including simple garbage collection.
Topic Objective
To provide an overview of
the section topics.
Lead-in

A major feature of the .NET
Framework common
language runtime is that the
runtime automatically
handles the allocation and
release of an object’s
memory resources.
Module 9: Memory and Resource Management 3


Developer Backgrounds
!
COM
#
Manually implement reference counting and handle
circular references
!
C++
#
Manually use the new operator and delete operator
!
Visual Basic
#
Accustomed to automatic memory management

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************

Your experience with memory management will vary depending upon your
development background. In certain situations, you will need to adapt your
programming practices to the automatic memory management that is provided
by the common language runtime.
COM Developers
COM developers are accustomed to implementing reference counting as a
manual memory management technique. Each time an object is referenced, a
counter is incremented. When a reference to an object goes out of scope, the
counter is decremented. When an object’s reference count reaches zero, the
object is terminated and its memory is freed.
The reference counting scheme is the source of many bugs. If the reference
counting rules are not followed precisely, objects may be freed prematurely or
unreferenced objects may accumulate in memory.
Circular references are also a common source of bugs. A circular reference
occurs when a child object has a reference to a parent object, and the parent
object has a reference to the child object. Circular references prevent either
object from being released or destroyed. The only solution is for the parent and
child objects to agree on a fixed pattern of usage and destruction, such as where
the parent always deletes the child first.
When you develop applications in a managed language, the runtime’s garbage
collector eliminates the need for reference counting and, as a result, the bugs
that can arise from this manual memory management scheme.
Topic Objective
To discuss various
developer backgrounds with
regard to memory
management.
Lead-in
Your experience with
memory management will

vary depending upon your
development background.
4 Module 9: Memory and Resource Management


C++ Developers
C++ developers are accustomed to the tasks that are related to manual memory
management. In C++, when you allocate memory for an object by using the
new operator, you must release the object’s memory by using the delete
operator. This can lead to errors such as forgetting to release an object and
causing a memory leak, or attempting to access memory for an object that has
already been released.
When you develop applications by using the Managed Extensions for C++, or
another managed language, you do not have to use the delete operator to release
an object. The garbage collector does this for you automatically when the object
is no longer being used by the application.
C++ developers may be accustomed to avoiding the use of short-term objects
because of the associated cost of manually managing the memory for these
objects. For managed short-term objects that are created and then go out of
scope between collections, the cost of allocating and releasing memory is
extremely low.
In the .NET Framework, the garbage collector is actually optimized to manage
objects with short lifetimes. When you develop managed applications, it is
appropriate to use short-term objects in situations where they simplify your
code.
Visual Basic Developers
Microsoft Visual Basic
®
developers are accustomed to automatic memory
management. If you are a Visual Basic developer, the programming practices

with which you are familiar apply to the majority of the managed objects that
you create in the .NET Framework. However, you should take special note of
the suggested design pattern for a Dispose method to use when you create or
use objects that encapsulate unmanaged resources.
Module 9: Memory and Resource Management 5


Manual vs. Automatic Memory Management
!
Manual Memory Management
#
Programmer manages memory
!
Common Problems
#
Failure to release memory
#
Invalid references to freed memory
!
.NET Runtime Provides Automatic Memory Management
#
Eases programming task
#
Eliminates a potential source of bugs

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************

Manual memory management requires that you manage the allocation and
deallocation of blocks of memory. The NET Framework common language
runtime provides automatic memory management so that you are freed from
this time-consuming and difficult task.
Manual Memory Management
The following table provides examples of manual memory management in
different programming languages, C and C++, and in COM.
Language or
environment

Example of manual memory management

C malloc and free functions
C++ new and delete operators
COM AddRef and Release reference counting methods

Automatic Memory Management in the .NET Framework
The .NET Framework common language runtime automatically handles
managed object memory and manages references to these objects, releasing
managed objects when they are no longer being used. This automatic memory
management eliminates the possibility of programming errors that can cause
memory leaks and the use of memory that has already been freed. With
automatic memory management, you no longer have to deal with complex bugs
that are associated with reference counting, circular reference leaks, or dangling
references.
Topic Objective
To introduce the advantages
of automatic memory
management in the .NET
Framework.

Lead-in
Manual memory
management requires that
you manage the allocation
and deallocation of blocks of
memory.
6 Module 9: Memory and Resource Management


Memory Management of .NET Framework Types
!
Instances of Value Types Use Stack Memory
#
Allocation and deallocation are automatic and safe
!
Managed Objects Are Reference Types and Use Heap
Memory
#
Created by calls to the new operator
#
Freed by garbage collection

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In the .NET Framework, all values have a type, which may be a value type or a
reference type. Each value’s type affects how that value is managed in memory.
Instances of Value Types

Instances of value types are stored in memory that is allocated on the stack.
Allocation and deallocation of memory occur automatically as follows:
!
Allocation
Memory for an instance of a value type is created when the activation record
for its scope is pushed on to the stack.
!
Deallocation
Memory is deallocated when the scope’s activation record, which contains
the value type instance, is popped from the stack.

Value types are always accessed directly. You cannot create a reference to a
value type, and therefore you cannot refer to a value instance that has been
deallocated. As a result, there is no danger of creating a dangling reference to a
value type.
Topic Objective
To explain how a value’s
type affects how the value is
managed in memory.
Lead-in
In .the NET Framework, all
values have a type, which
may be a value type or a
reference type.
Module 9: Memory and Resource Management 7


Instances of Reference Types
Managed objects are reference types, which you create by calls to the new
operator. The memory of these objects is allocated in the common language

runtime managed heap. You can access reference types only through a
reference to that storage. The use of references enables garbage collection to
track outstanding references to a particular instance and to free that object’s
heap memory when appropriate.
A managed object’s heap memory is only released through garbage collection
when there are no reachable references to that object. This mechanism ensures
that there will be no invalid references to the object’s freed memory and thus no
dangling references.
8 Module 9: Memory and Resource Management


Simple Garbage Collection
!
Simple Garbage Collection Algorithm
#
Wait until managed code threads are in a safe state
#
Build a graph of all reachable objects
#
Move reachable objects to compact heap
- Unreachable objects’ memory is reclaimed
#
Update references to all moved objects
!
Reference Cycles Are Handled Automatically

*****************************
ILLEGAL FOR NON
-
TRAINER USE

******************************
Typically, garbage collection is triggered when an application creates an object,
and there is not enough space left in the heap to provide memory for the object.
Alternatively, you can invoke garbage collection programmatically. This
process is discussed in Optimizing Garbage Collection in this module.
The Garbage Collection Algorithm
Whether garbage collection occurs automatically or you invoke it
programmatically, the garbage collection algorithm is used to find any objects
in the heap whose memory can be reclaimed. Such objects include objects that
are no longer being used by the application. If garbage collection can reclaim
enough objects to free sufficient memory, memory for the new objects can be
allocated. Otherwise, an OutOfMemoryException is thrown.
For the sake of simplicity, this topic describes the simple garbage collection
process. The finalization phase and optimization details are discussed in
Implicit Resource Management in this module.
Simple Garbage Collection Process
Simple garbage collection uses the following process:
1. Waits until other managed threads reach a safe state, for example,
suspended.
The garbage collection process modifies managed objects and their
references. Therefore it must first wait until other managed threads are
suspended.
2. Builds a graph of all reachable objects.
3. Compacts the heap by moving reachable objects.
By moving reachable objects down in the heap, garbage collection reclaims
the space in the heap that was used by unreachable objects.
4. Updates all application references to moved objects.

Topic Objective
To explain how simple

garbage collection works in
the .NET Framework.
Lead-in
Garbage collection is
triggered when an
application creates an
object, and there is not
enough space left in the
heap to provide memory for
the object.
Module 9: Memory and Resource Management 9


Building the Graph of Reachable Objects
Garbage collection accesses the collection of root references that are maintained
by the runtime. Each application has a logical collection of root references. The
collection contains all of the managed object references from global and static
objects and local variables that are currently on the stack and in CPU registers.
To build the graph of reachable objects, garbage collection performs the
following actions.
1. It adds all of the objects that are referenced by each root reference.
2. It recursively adds objects that are referenced by any added object.

Before an object is added to the graph, garbage collection checks to ensure that
the object is not already in the graph. This check prevents garbage collection
from entering an infinite loop that is caused by circular references.
At the end of the process, any object that is not in the reachable object graph is
considered unreachable and therefore garbage.
Reference Cycles Handled Automatically
An object is reachable only if there is a path from a root reference to that object.

Therefore, reference cycles between unreachable objects will not prevent the
objects’ memory from being released by the garbage collection process. For
example, if A references B and B references A, then both objects will be
garbage collected when they are no longer reachable from a root reference.
10 Module 9: Memory and Resource Management


Multimedia: Simple Garbage Collection

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
This animation illustrates the .NET Framework common language runtime
garbage collection process.

Compiler optimization is disabled in this scenario to prevent an object
from becoming eligible for garbage collection earlier than would be expected.
Otherwise, the compiler could optimize away assignments to local variables
that are never observed by a later read. This optimization could result in an
object being subject to garbage collection before its reference is assigned to
null.

!
The common language runtime allocates memory resources for reference
type objects in the section of the application’s memory that is called the
managed heap.
!
When there is insufficient space in the managed heap, the common language

runtime executes the garbage collection algorithm to remove objects that are
no longer being used by the application.

Topic Objective
To illustrate the .NET
Framework garbage
collection process.
Lead-in
This animation illustrates the
.NET Framework common
language runtime’s garbage
collection process.
To launch the animation,
click the button in the lower
left corner of the slide. To
play the animation, click the
Simplified Garbage
Collection button at the top
of the screen, and then click
the play button in the lower
left corner of the screen.
Note
Module 9: Memory and Resource Management 11


The steps of the algorithm are as follows:
1. After all other managed threads reach a safe state, for example suspended,
garbage collection builds a graph of all of the objects that are reachable
from the root references.
2. Before an item is added to the graph, a check is made to ensure that the

object is not already in the graph.
This check ensures that circular references are handled without garbage
collection entering an infinite loop.
3. After all of the root references and added objects have been processed, any
objects that are not in the graph are not reachable by the application.
The memory for these objects can be reclaimed when the heap is
compacted.
4. The remaining objects are moved down in the heap to fill the gaps.
5. The garbage collection process must then update all references to the moved
objects.

12 Module 9: Memory and Resource Management


Non-Memory Resource Management
!
Implicit Resource Management
!
Explicit Resource Management

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Managed objects sometimes encapsulate control over resources that are not
managed by the runtime. Examples of these non-memory resources include
window handles, file handles, and database connections.
You need implicit and explicit ways to free these resources. Garbage collection
provides implicit resource management of an object by calling the object’s

finalize code.
The client of an object provides explicit resource management by calling the
Dispose method on the IDisposable interface of the object when the client is
finished using the object.
Topic Objective
To provide an overview of
non-memory resource
management, which is
discussed in the following
topics.
Lead-in
Managed objects
sometimes encapsulate
control over resources that
are not managed by the
runtime.
For Your Information
This topic is an introduction
to handling non-memory
resources implicitly and
explicitly. Tell students that
the next two sections cover
these areas in detail. You
should not spend much time
on this slide.
Module 9: Memory and Resource Management 13


"
""

"

Implicit Resource Management
!
Finalization
!
Garbage Collection with Finalization
!
Finalization Guidelines
!
Controlling Garbage Collection

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
The .NET Framework common language runtime provides the means for
notifying an object before it is destroyed so that it can clean up and release non-
memory resources.
In this section, you will learn how to take advantage of this feature.
Topic Objective
To provide an overview of
the section topics.
Lead-in
The .NET Framework
common language runtime
provides the means for
notifying an object before it
is destroyed so that it can

clean up and release non-
memory resources.
14 Module 9: Memory and Resource Management


Finalization
!
Finalize Code Called by Garbage Collection
!
In C#, the Finalize Code Is Provided by a Destructor
!
Use C# Destructor to Implicitly Close a FileStream
class Foo {
private System.IO.FileStream fs;
//
public Foo() {
fs = new System.IO.FileStream(
"bar", FileMode.CreateNew);
}
~Foo() { fs.Close(); }
}
class Foo {
private System.IO.FileStream fs;
//
public Foo() {
fs = new System.IO.FileStream(
"bar", FileMode.CreateNew);
}
~Foo() { fs.Close(); }
}


*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Implicit management of resources ensures that an object can properly clean up
its resources at some time in the future when there are no longer any valid
references to the object.
If an object provides finalize code in its destructor, the garbage collection
process calls this code when there are no longer any valid references to the
object. This phase of garbage collection is referred to as finalization.
Finalization allows an object to properly cleanup before its memory resources
are freed.
Using a Destructor for Finalization
In C#, the Finalize method is not directly accessible, and you cannot call or
override the Finalize method. You must place code to be executed during
finalization inside a C# destructor. The syntax for a C# destructor is the tilde
operator (~), followed by the class name and a block of statements that will be
executed during finalization. The following example shows the C# destructor
syntax for a class named Foo.
~Foo() {
// perform some cleanup operation here
}

Topic Objective
To define and describe
finalization in garbage
collection.
Lead-in

Implicit management of
resources ensures that an
object can properly clean up
its resources at some time
in the future when there are
no longer any valid
references to the object.
Module 9: Memory and Resource Management 15


This code implicitly translates to the following:
protected override void Finalize() {
try {
// do something
}
finally {
base.Finalize();
}
}

Destructors are not inherited. When the finalization code of an object is
executed and the object is destructed, the destructors in the inheritance chain of
that object are called in order, from the most derived destructor to the least
derived destructor.
Differences Between C# and C++ Destructors
C# destructors and C++ destructors differ in several important ways, as shown
in the following table.
Destructor Characteristics

C# destructors Execute non-deterministically

Automatically invoked at any time after an object becomes eligible
for garbage collection
Not guaranteed to run in any specific order, even if one object
contains or refers to another
Cannot be invoked explicitly
C++ destructors Execute deterministically
Run in the order they are called
Can be invoked explicitly

An Example of Implicit Resource Management
A class Foo has a constructor that creates a FileStream. To ensure that the
buffer of the FileStream object is properly flushed, the class Foo provides
implicit management of the resource through destructor code that closes the
FileStream, as shown in the following code:
class Foo {
private System.IO.FileStream fs;
//
public Foo() {
fs = new System.IO.FileStream("bar", FileMode.CreateNew);
}
~Foo() { fs.Close(); }
}

Implicit management of resources may not be adequate in all circumstances. In
the preceding example, full access by other objects to the file that is opened by
a Foo object may be delayed for an indeterminate amount of time after the Foo
object no longer needs the resource. Therefore, you typically need to use an
explicit form of resource management. For more information about explicit
resource management, see Explicit Resource Management in this module.
16 Module 9: Memory and Resource Management



Garbage Collection with Finalization
!
Runtime Maintains a List of Objects That Require Finalization
#
Finalization queue
!
Garbage Collection Process Invoked
!
Unreachable Objects Requiring Finalization
#
References added to freachable queue
#
Objects are now reachable and not garbage
!
Move Reachable Objects to Compact the Heap
#
Unreachable objects' memory is reclaimed
!
Update References to All Moved Objects

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Finalization adds to the complexity and increases performance overhead of the
basic garbage collection process, as it was described in Simple Garbage
Collection in this module.

The .NET Framework common language runtime maintains a list of managed
objects that require finalization. This list is known as the finalization queue and
is used during garbage collection to provide implicit resource management.
Garbage collection is typically invoked when the creation of a new object
requires more space in the managed heap than is currently available.
After waiting for all other managed threads to be suspended, garbage collection
with finalization proceeds as follows:
1. Garbage collection builds a graph of all reachable objects, as described in
Simple Garbage Collection in this module.
Any managed object that is not in the graph is unreachable.
2. Garbage collection checks the finalization queue to see if an unreachable
object requires finalization.
If an unreachable object requires finalization, it is removed from the
finalization queue, and a reference to the object is placed in the freachable
(pronounced F-reachable) queue. The freachable queue is part of the root
references of an application. The object is therefore now considered
reachable and is no longer garbage.
3. Garbage collection compacts the heap and updates references to all moved
objects.
At this point, the memory resources for the unreachable objects have been
freed.
4. Garbage collection allows the application to continue normal operation.

At this point, the finalization phase of the garbage collection process can
commence on a separate thread.
Topic Objective
To describe the initial
process of garbage
collection with finalization.
Lead-in

Finalization adds to the
complexity and increases
performance overhead of
the basic garbage collection
process, as it was described
in Simple Garbage
Collection in this module.
Module 9: Memory and Resource Management 17


Garbage Collection with Finalization (continued)
!
Finalize Thread Runs
#
Executes freachable objects' Finalize methods
#
References removed from freachable queue
#
Unless resurrected, objects are now garbage
#
May be reclaimed next time garbage collection occurs

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
After the memory resources for the unreachable objects are freed and the
application has continued normal operation, the finalization phase of garbage
collection commences on a separate thread.

The Finalization Phase
As the application runs, a special runtime thread removes references to objects
from the freachable queue and calls the finalize code of those objects.
Therefore, it is important that this code does not depend upon the identity of the
thread. For example, the method should not depend on thread local storage.
After an object has been finalized and removed from the freachable queue, it
becomes unreachable again as long as that object has not been resurrected. An
object is resurrected if it becomes reachable from an application root after
previously being unreachable.
However, the object’s memory resources are not freed at this time. The
reclamation of the object’s memory resources must wait until garbage
collection occurs next.
Topic Objective
To describe the latter part of
the process of garbage
collection with finalization.
Lead-in
After the memory resources
for the unreachable objects
are freed and the application
has continued normal
operation, the finalization
phase of garbage collection
commences on a separate
thread.
18 Module 9: Memory and Resource Management


Resurrection
Resurrection of an object occurs when a previously unreachable object becomes

reachable from an application root during finalization. For example, the finalize
code for an object may assign to a global or static variable a reference to the
object itself. The object is now reachable and is not subject to garbage
collection.
Issues with Resurrection
You should avoid resurrection when possible because the object’s finalize code
has been called and may have released resources that are required for the
object’s proper operation, even if the object’s memory is valid.
For example, when the destructor of the Foo class that was shown in An
Example of Implicit Resource Management in this module executes its
finalization code, the file will close, and the other methods of Foo that require
an open FileStream may not be able to successfully complete.
In addition, when a resurrected object becomes unreachable sometime in the
future, its finalize code will not be called unless the object has called the
GC.ReRegisterForFinalize method.
You should also note that even if the finalize code of a class does not resurrect
an object, that object may still be resurrected, as when another object that refers
to the object is resurrected. Thus, all objects should be able to handle
resurrection. For more information about resurrection and finalization, see
Controlling Garbage Collection in this module.
Module 9: Memory and Resource Management 19


Multimedia: Garbage Collection

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************

This animation illustrates the .NET Framework common language runtime
garbage collection process, including finalization.

Compiler optimization is disabled in this scenario to prevent an object
from becoming eligible for garbage collection earlier than would be expected.
Otherwise, the compiler could optimize away assignments to local variables
that are never observed by a later read. This optimization could result in an
object being subject to garbage collection before its reference is assigned to
null.

In this animation, you will learn that:
!
The .NET Framework common language runtime allocates memory
resources for objects in the section of the application’s memory that is
called the managed heap.
!
The finalization queue holds references to objects whose classes require
finalization.
!
The freachable queue is a special kind of root reference whose entries are
references to objects that are ready to have their finalize code invoked. An
freachable reference keeps the object alive.
!
The nondeterministic release of memory and non-memory resources is
another significant difference between .NET Framework and C++
destructors.

Topic Objective
To illustrate how garbage
collection, including

finalization, works.
Lead-in
This animation illustrates the
.NET Framework common
language runtime garbage
collection process, including
finalization.

To launch the animation,
click the button in the lower
left corner of the slide. To
play the animation, click the
play button in the lower left
corner of the screen.
Note

×