10266A_09.ppt
- Количество слайдов: 18
Module 9 Managing the Lifetime of Objects and Controlling Resources
Module Overview • Introduction to Garbage Collection • Managing Resources
Lesson 1: Introduction to Garbage Collection • The Object Life Cycle • Managed Resources in the. NET Framework • How Does the Garbage Collector Work? • Defining a Destructor • The GC Class • Demonstration: Implementing a Destructor
The Object Life Cycle 1 • Block of memory allocated 2 • Memory converted into an object (constructor) 3 • Object used in application 4 • Object tidied up (destructor) 5 • Memory reclaimed
Managed Resources in the. NET Framework Value Types Reference Types • Usually created on the stack • Created on the heap • Destroyed automatically when • Support multiple references to they go out of scope • Never fragmented • Fast to allocate and deallocate same object • Can only be destroyed when the last reference disappears • Can cause memory fragmentation private void My. Method(…) { My. Struct a = …; Date. Time z = …; double y = …; int x = …; … } // x, y, z, and a disappear here • Managed by the garbage collector • More expensive to manage string s = …; My. Class c = …; private void My. Method 2(…) { string t = s; My. Class d = c; … // References t and d disappear here // Objects s and c remain on the heap }
How Does the Garbage Collector Work? Stack Heap Location 2 Refs: 1, 4 Location 3 Refs: 1, 4 Location 1 Refs: James > Finally: 6 Location • Update Pointers 2 John > 4 Refs: • Start Finalization thread 4 freachable Freachable Location 4 Refs: 5 Location 6 Refs: 8 Location 6 Refs: Location 9 Refs: Location 3 Refs: Finalizer Location 5 Refs: 6 Location 8 Refs: 6 • Mark all objects as dead James > 6 John > 4 5 Location • Map which objects should stay alive 1 4 7 Refs: • Add finalizable dead objects to the freachable 2, 3, 4 2 queue 5 • Remove dead objects and defragment heap • Update pointers • Start finalization thread
Defining a Destructor class Employee {. . . ~Employee { // Destructor logic. } } Destructors never take parameters The compiler converts the destructor to an override of the Finalize method Use a tilde (~) followed by the class name to define a destructor Value types cannot define a destructor class Employee {. . . protected override void Finalize() { try { // Destructor logic. } finally { base. Finalize(); } } }
The GC Class Name Description Collect Forces garbage collection Wait. For. Pending. Finalizers Suspends the current thread until all of the objects in the freachable queue have been finalized Suppress. Finalize Prevents finalization of the object passed as the parameter Re. Register. For. Finalize Requests finalization for an object that has either already been finalized or had finalization suppressed Add. Memory. Pressure Informs the runtime that you must allocate a large block of unmanaged memory Remove. Memory. Pressure Informs the runtime that you have released a large block of unmanaged memory
Demonstration: Implementing a Destructor In this demonstration, you will: • Add a destructor to the Employee class • Use the Add. Memory. Pressure method of the GC class to increase the pressure on the garbage collector • Use the Wait. For. Pending. Finalizers method to halt the current thread until all objects currently in the freachable queue have finalized
Lesson 2: Managing Resources • Why Manage Resources in a Managed Environment? • What Is the Dispose Pattern? • Managing Resources in Your Applications • Demonstration: Using the Dispose Pattern
Why Manage Resources in a Managed Environment? • Unmanaged resources are not subject to garbage collection: • You must take responsibility for releasing them when an object is finalized • Failing to dispose of unmanaged objects properly can result in data loss Example: Files may be locked, preventing other applications from using them Example: Data cached in memory may be lost if resources are not managed properly Example: Connections to databases are often limited
What Is the Dispose Pattern? class Log. File. Writer : …, IDisposable { private bool is. Disposed = false; ~Log. File. Writer() { Dispose(false); } public void Dispose() { Dispose(true); GC. Suppress. Finalize(this); } protected virtual void Dispose(bool is. Disposing) { if (!is. Disposed) { if (is. Disposing) { // clean up managed resources; } // clean up unmanaged resources is. Disposed = false; base. Dispose(is. Disposing) } } } Implement the IDisposable interface Track the object status Add a destructor if you must ensure that the object is disposed of Add a public Dispose method that disposes of resources and suppresses subsequent finalization Add a virtual Dispose method that takes a boolean value indicating whether the object is currently disposing (or if false, finalizing)
Managing Resources in Your Applications Try/Finally: • Only use when using is not possible • Exception safe Using: • Use wherever possible • Exception safe • Only works with objects that implement the IDisposable interface • Should not be confused with the using statement for importing namespaces Disposable. Object disp = new Disposable. Object(); try { // Use the object. } finally { disp. Dispose(); } using(Disposable. Object disp = new Disposable. Object()) { // Use the object. } // OR Disposable. Object disp 2 = new Disposable. Object(); using(disp 2) { // Use the object. }
Demonstration: Using the Dispose Pattern In this demonstration, you will: • Implement the IDisposable interface • Use a using statement to automatically dispose of an object • Manually dispose of an object
Lab: Managing the Lifetime of Objects and Controlling Resources • Exercise 1: Implementing the IDisposable Interface • Exercise 2: Managing Resources Used by an Object Logon information Virtual machine 10266 A-GEN-DEV User name Student Password Pa$$w 0 rd Estimated time: 45 minutes
Lab Scenario
Lab Review • How do you alias a Dispose method? • What is the syntax of the using statement?
Module Review and Takeaways • Review Questions • Best Practices
10266A_09.ppt