Implicit Resource Management Introduce the finalization phase of the garbage collection process.. Language or environment Example of manual memory management C malloc and free functions
Trang 1Contents
Overview 1
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
Trang 2and 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
Trang 3Instructor 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
Trang 4Demonstrations
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
Trang 5Module 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
Trang 7Overview
! 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
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
Trang 8" 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
Trang 9***************************** 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
Your experience with
memory management will
vary depending upon your
development background
Trang 10C++ 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
Trang 11Manual vs Automatic Memory Management
! Manual Memory Management
! Common Problems
! .NET Runtime Provides Automatic Memory Management
***************************** 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
management requires that
you manage the allocation
and deallocation of blocks of
memory
Trang 12Memory Management of NET Framework Types
! Instances of Value Types Use Stack Memory
! Managed Objects Are Reference Types and Use Heap Memory
***************************** 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
Trang 13Instances 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
Trang 14Simple Garbage Collection
! Simple Garbage Collection Algorithm
- Unreachable objects’ memory is reclaimed
! 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
Trang 15Building 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
Trang 16Multimedia: 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
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
Trang 17The 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
Trang 18Non-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
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
Trang 19" 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
Trang 20Finalization
! 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;
***************************** 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 }
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
Trang 21This 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;
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
Trang 22Garbage Collection with Finalization
! Runtime Maintains a List of Objects That Require Finalization
! Garbage Collection Process Invoked
! Unreachable Objects Requiring Finalization
! Move Reachable Objects to Compact the Heap
! 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
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
Trang 23Garbage Collection with Finalization (continued)
! Finalize Thread Runs
***************************** 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
Trang 24Resurrection
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
Trang 25Multimedia: 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++
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
Trang 26Finalization Guidelines
! Avoid Finalization and Destructors If Possible
! If You Require Finalization, Finalize Code Should:
! Classes with Finalization Should:
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
This topic provides guidelines for handling finalization To avoid problems that result from the NET Framework’s nondeterministic ordering of calls to finalize code, you may need to use explicit resource management in addition to careful design
Avoid Finalization if Possible
You should only implement finalization, or implement a destructor in C#, on classes that require finalization If your class has only managed references and does not have to manage non-memory resources, you should not implement
finalize code Finalization adds overhead and complexity, and delays the
reclamation of an object’s memory resources
Implementing Finalization
If you must implement finalization, you should obey the following guidelines:
! Avoid calling other objects in finalization code
In your finalization code, free any external resources that your object is holding on to However, you should avoid calling other objects, for example, contained objects, because their finalize code may have already been called The NET Framework common language runtime does not specify any order on its invocation of the finalize code of freachable objects
Therefore, if an object of type Foo refers to an object of type Bar, you cannot know whether the finalize code of Foo will be called before or after the finalize code of Bar This nondeterminism may cause problems if the finalize code of Foo calls a method in Bar that requires a resource that is released by Bar in its finalize code
! Avoid assumptions about thread ID
As previously noted, finalization code should not make any assumptions about the thread ID
Topic Objective
To alert students to issues
that are associated with
finalization
Lead-in
This topic provides
guidelines for handling
finalization
Trang 27! Ensure that the Finalize code of your base class is called
This call is performed automatically by the C# destructor syntax
! Avoid references to other objects
A class that requires finalization should avoid references to other objects because a finalizable object will prolong its own lifetime and the lifetime of objects that it references If possible, you should factor such classes into the following two classes:
• One class that contains the resource that requires management and has the finalize code but has no other object references
• A second class that holds the references to other objects but has no finalize code
Trang 28Controlling Garbage Collection
! To Force Garbage Collection
! To Suspend Calling Thread Until Thread’s Queue of Finalizers
void System.GC.ReRegisterForFinalize(object obj);
void System.GC.SuppressFinalize(object obj);
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
The System.GC class of the NET Framework contains methods that can be used to control garbage collection The Collect method with no arguments
forces the collection of all generations, as in the following code:
void System.GC.Collect();
For more information about generations, see Generations in this module Finalizers are run on a separate thread of execution When the
WaitForPendingFinalizers method is called, the current thread is suspended
until the queue of finalizers that are waiting to run is empty Because the running of finalizers may trigger another garbage collection, which may, in turn, re-queue new finalizers, there is no guarantee that the call to
WaitForPendingFinalizers will terminate
void System.GC.WaitForPendingFinalizers();
After the garbage collection process calls an object’s finalize code, garbage collection assumes that there is no need to call it again However, if an object is
resurrected, the ReRegisterForFinalize method may be called to force garbage
collection to call the object’s finalize code again the next time the object is
destroyed Note that if ReRegisterForFinalize is called multiple times, the
object’s finalize code will also be called multiple times
void System.GC.ReRegisterForFinalize(object obj);
If an object that has finalize code no longer requires finalization to manage its
resources, the object may call the SuppressFinalize method to improve
performance For example, an object that supports explicit resource
management should call the SuppressFinalize method when it releases its
resources, as in the following code:
void System.GC.SuppressFinalize(object obj);
Topic Objective
To introduce techniques to
control garbage collection
Lead-in
The System.GC class of the
.NET Framework contains
methods that can be used to
control the garbage
collection process
Trang 29Demonstration: Finalization
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
This demonstration shows how garbage collection handles finalization and resurrection
// This method demonstrates how the GC works
private static void Introduction() { Display(0,
"\n\nDemo start: Introduction to Garbage Collection.", +1); // Create a new DerivedObj in the managed heap
// Note: Both BaseObj and DerivedObj constructors are called DerivedObj obj = new DerivedObj("Introduction");
obj = null; // We no longer need this object // The object is unreachable so forcing a GC causes it to be // finalized
(Code continued on the following page.)
Topic Objective
garbage collection handles
finalization and resurrection
Lead-in
This demonstration shows
how garbage collection
handles finalization and
resurrection
For Your Information
Use the debugger to step
through the code while you
point out features and ask
students what they think will
happen next In this section
run the Introduction and
ResurrectionDemo
methods
Trang 30// This is the same test as above with one slight variation obj = new DerivedObj("Introduction");
// obj = null; // Variation: this line is commented out Collect();
WaitForFinalizers();
// If compiler optimization was turned on:
// Notice that we get identical results as above:
// the destructor’s Finalize code // runs because the just in time compiler’s optimizer // knows that obj is not referenced later in this function // Now we explicitly release the object and the destructor’s // Finalize code is run
// If compiler optimization was turned off // we now see the finalization called otherwise nothing obj = null;
Collect();
WaitForFinalizers();
Display(-1, "Demo stop: Introduction to Garbage Collection.", 0); }
// Resurrection // This reference is accessed in the ResurrectObj.Finalize // code and is used to create a strong reference to an // object (resurrecting it)
static public ResurrectObj ResObjHolder; // Defaults to null // This method demonstrates how the GC supports resurrection // NOTE: Resurrection is discouraged
private static void ResurrectionDemo() { Display(0, "\n\nDemo start: Object Resurrection.", +1); // Create a ResurrectObj
ResurrectObj obj = new ResurrectObj("Resurrection");
// Destroy all strong references to the new ResurrectionObj obj = null;
// Force the GC to determine that the object is unreachable Collect();
WaitForFinalizers();
// You should see the Finalize code called
// However, the ResurrectObj's Finalize code // resurrects the object keeping it alive
// It does this by placing a // reference to the dying-object in Application.ResObjHolder // You can see that ResurrectObj still exists because
// the following line doesn't raise an exception
ResObjHolder.Display("Still alive after Finalize called");
(Code continued on the following page.)
Trang 31// Prevent the ResurrectObj object from resurrecting // itself again,
// You should see the Finalize code called
Display(-1, "Demo stop: Object Resurrection.", 0);
}