Chapter 5: Garbage Collection

Overview

Memory management, and in particular the cleaning up of any resources that are no longer needed by an application, is an important service provided by the .NET Framework. The aim of this chapter is to make sure you understand at a fairly detailed level how the main .NET resource cleanup system, the garbage collector, works, and how best to use the garbage collection services in your code. We also examine show the best methods for implementing objects that can be cleared up by the garbage collector. In more detail, we will cover:

  • The main advantages of garbage collection versus alternative techniques; in short, why Microsoft decided on garbage collection as the best solution

  • The way the garbage collector works, including details of the algorithm it uses at present, and the way it hijacks your threads

  • Implementing Dispose() and Finalize()

  • Weak references

We'll start the chapter by investigating the advantages of garbage collection as compared to the alternatives.

For most of the book, the term resource indicates some specific unmanaged or managed resource that is embedded in or linked to an assembly, such as a bitmap. However, in this chapter, we use the term resource more generically to mean any item that occupies memory or system resources. This could be, for example, a plain managed object, or on the unmanaged side it could be an unmanaged object or an external resource such as a file or window handle. We should also differentiate between 'normal' resources - such as managed memory -for which the GC's finalization mechanism is adequate, and 'precious' resources, such as database connections, which really need to be cleaned up as soon as the program has finished with them.



Advanced  .NET Programming
Advanced .NET Programming
ISBN: 1861006292
EAN: 2147483647
Year: 2002
Pages: 124

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net