Information Technology Reference
In-Depth Information
result, the object remains in the finalization queue, even though finaliza-
tion is not needed. If you have the choice, Dispose() is better than Close().
Yo u ' l l l e a r n a l l t h e g o r y d e t a i l s i n I t e m 1 8 .
Dispose() does not remove objects from memory. It is a hook to let objects
release unmanaged resources. That means you can get into trouble by
disposing of objects that are still in use. The examples above use
SQLConnection. The SQLConnection's Dispose() method closes the con-
nection to the database. After you dispose of the connection, the
SQLConnection object is still in memory, but it is no longer connected to
a database. It's in memory, but it's not useful. Do not dispose of objects
that are still being referenced elsewhere in your program.
In some ways, resource management can be more difficult in C# than it
was in C++. You can't rely on deterministic finalization to clean up every
resource you use. But a garbage-collected environment really is much simpler
for you. The vast majority of the types you make use of do not implement
IDisposable. Less than 100 classes in the .NET Framework implement
IDisposable—that's out of more than 1,500 types. When you use the ones
that do implement IDisposable, remember to dispose of them in all cases.
Yo u s h o u l d w r a p t h o s e o b j e c t s i n using clauses or try / finally blocks.
Whichever you use, make sure that objects get disposed properly all the
time, every time.
Item 16: Avoid Creating Unnecessary Objects
The Garbage Collector does an excellent job of managing memory for you,
and it removes unused objects in a very efficient manner. But no matter
how you look at it, allocating and destroying a heap-based object takes
more processor time than not allocating and not destroying a heap-based
object. You can introduce serious performance drains on your program
by creating an excessive number of reference objects that are local to your
methods.
So don't overwork the Garbage Collector. You can follow some simple
techniques to minimize the amount of work that the Garbage Collector
needs to do on your program's behalf. All reference types, even local vari-
ables, are allocated on the heap. Every local variable of a reference type
becomes garbage as soon as that function exits. One very common bad
practice is to allocate GDI objects in a Windows paint handler:
 
 
Search WWH ::




Custom Search