Information Technology Reference
In-Depth Information
2
.NET Resource Management
The simple fact that .NET programs run in a managed environment has a
big impact on the kinds of designs that create effective C#. Taking advan-
tage of that environment requires changing your thinking from other envi-
ronments to the .NET Common Language Runtime (CLR). It means
understanding the .NET Garbage Collector. An overview of the .NET
memory management environment is necessary to understand the spe-
cific recommendations in this chapter, so let's get on with the overview.
The Garbage Collector (GC) controls managed memory for you. Unlike
native environments, you are not responsible for most memory leaks,
dangling pointers, uninitialized pointers, or a host of other memory-
management issues. But the Garbage Collector is not magic: You need to
clean up after yourself, too. You are responsible for unmanaged resources
such as file handles, database connections, GDI+ objects, COM objects,
and other system objects. In addition you can cause objects to stay in
memory longer than you'd like because you've created links between them
using event handlers or delegates. Queries, which execute when results are
requested, can also cause objects to remain referenced longer than you
would expect. Queries capture bound variables in closures, and those
bound variables are reachable until the containing results have gone out of
scope.
Here's the good news: Because the GC controls memory, certain design
idioms are much easier to implement. Circular references, both simple
relationships and complex webs of objects, are much easier. The GC's
Mark and Compact algorithm efficiently detects these relationships and
removes unreachable webs of objects in their entirety. The GC determines
whether an object is reachable by walking the object tree from the appli-
cation's root object instead of forcing each object to keep track of refer-
ences to it, as in COM. The EntitySet class provides an example of how
this algorithm simplifies object ownership decisions. An Entity is a col-
lection of objects loaded from a database. Each Entity may contain refer-
ences to other Entity objects. Any of these entities may also contain links
69
 
 
 
Search WWH ::




Custom Search