Tài liệu Module 9: Memory and Resource Management - Pdf 96



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 ManagementInformation 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.

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

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

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.
!

"

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

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

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
******************************

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

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

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.

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

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 "
""

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(); }
}

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
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.

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.

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
******************************

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


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status