Module 9: Memory and Resource Management
Overview
Memory Management Basics
Non-Memory Resource Management
Implicit Resource Management
Explicit Resource Management
Optimizing Garbage Collection
Memory Management Basics
Developer Backgrounds
Manual vs. Automatic Memory Management
Memory Management of .NET Framework Types
Simple Garbage Collection
Developer Backgrounds
COM
C++
Developers manually implement reference counting and handle circular references Developers manually use the new operator and delete operator
Visual Basic
Developers accustomed to automatic memory management
Manual vs. Automatic Memory Management
Manual memory management
Programmer manages memory
Common problems with manual memory management
Failure to release memory
Invalid references to freed memory
Automatic memory management provided with .NET Runtime
Eases programming task
Eliminates a potential source of bugs
Memory Management of .NET Framework Types
Instances of value types use stack memory
Allocation and deallocation are automatic and safe
Instances of reference types use heap memory
Created by calls to the new operator
Freed by garbage collection
Simple Garbage Collection
Simple garbage collection algorithm takes these steps
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
Multimedia: Simple Garbage Collection
Non-Memory Resource Management
Implicit resource management
Explicit resource management
Implicit Resource Management
Finalization
Garbage Collection with Finalization
Finalization Guidelines
Controlling Garbage Collection
Finalization
Finalize code called by garbage collection
Class MyClass ' ... Public Sub New() ‘Get some unmanaged resource End Sub Protected Overrides Sub Finalize() ‘Release unmanaged resource End Sub End Class
Garbage Collection with Finalization
Runtime maintains a list of objects that require finalization
Finalization queue
When the garbage collection process invoked:
References to unreachable objects requiring finalization are added to freachable queue Objects are now reachable and not garbage
Reachable objects are moved to compact the heap Unreachable objects' memory is reclaimed
Garbage Collection with Finalization (continued)
Finalize thread runs
Executes freachable objects' Finalize methods
References removed from freachable queue
Unless resurrected, objects are considered garbage
Objects may be reclaimed next time garbage collection occurs
Multimedia: Garbage Collection
Finalization Guidelines
Avoid finalizers if possible because finalization adds:
Performance costs
Complexity
Delay of memory resource release
If you require finalization, finalize code should:
Avoid calling other objects
Avoid making assumptions about thread ID
Classes with finalization should:
Avoid making references to other objects
Controlling Garbage Collection
To force garbage collection
System.GC.Collect() To suspend calling thread until thread’s queue of finalizers is empty System.GC.WaitForPendingFinalizers()
To allow a finalized resurrected object to have its finalizer called again
System.GC.ReRegisterForFinalize(obj as object) To request the system not to call the finalizer method System.GC.SuppressFinalize(obj as object)
Demonstration: Finalization
Explicit Resource Management
The IDisposable Interface and the Dispose Method
Temporary Resource Usage Design Pattern
The IDisposable Interface and the Dispose Method
Inherit from the IDisposable interface
Implement the Dispose method
Follow the .NET Framework SDK’s design pattern
Class ResourceWrapper Implements IDisposable ' see code example for details End Class
Demonstration: The IDisposable Interface
Temporary Resource Usage Design Pattern
Temporary resource use
Allocate a resource, use it, and dispose of it
Sub DoSomething() Dim r = New Resource(...) Try r.DoSomethingElse() Finally If (Not r Is Nothing) Then r.Dispose() End If End Try End Sub
Try and Finally
Optimizing Garbage Collection
Weak References
Generations
Additional Performance Features
Weak References
A weak reference allows an object to be collected if memory is low
Dim obj = New Object() ' create strong reference Dim wr = New WeakReference(obj) obj = Nothing ' remove strong reference ' ... obj = CType(wr.Target, Object) If (Not obj Is Nothing) Then ' garbage collection hasn’t occurred ' ... Else ' object was collected, reference is nothing ' ... End If
Demonstration: Weak References
Generations
To force garbage collection of generation 0 through a specified generation
System.GC.Collect(Generation As Integer)
To find out the generation of an object
System.GC.GetGeneration(obj As Object) As Integer
To return the maximum number of generations that the system currently System.GC.MaxGeneration As Integer supports
Demonstration: Generations
Additional Performance Features
Performance monitoring
Large object heap
Multiprocessor support
Lab 9.1: Memory and Resource Management
Review
Memory Management Basics
Non-Memory Resource Management
Implicit Resource Management
Explicit Resource Management
Optimizing Garbage Collection