Information Technology Reference
In-Depth Information
// usage:
void Func()
{
// The lifetime of s controls access to
// the system resource.
CriticalSection s = new CriticalSection ();
// Do work.
//...
// compiler generates call to destructor.
// code exits critical section.
}
This common C++ idiom ensures that resource deallocation is exception-
proof. This doesn't work in C#, however—at least, not in the same way.
Deterministic finalization is not part of the .NET environment or the C#
language. Trying to force the C++ idiom of deterministic finalization into
the C# language won't work well. In C#, the finalizer eventually executes,
but it doesn't execute in a timely fashion. In the previous example, the
code eventually exits the critical section, but, in C#, it doesn't exit the crit-
ical section when the function exits. That happens at some unknown time
later. You don't know when. You can't know when. Finalizers are the only
way to guarantee that unmanaged resources allocated by an object of a
given type are eventually released. But finalizers execute at nondetermin-
istic times, so your design and coding practices should minimize the need
for creating finalizers, and also minimize the need for executing the final-
izers that do exist. Throughout this chapter you'll learn when you must
create a finalizer, and how to minimize the negative impact of having one.
Relying on finalizers also introduces performance penalties. Objects that
require finalization put a performance drag on the Garbage Collector.
When the GC finds that an object is garbage but also requires finalization,
it cannot remove that item from memory just yet. First, it calls the final-
izer. Finalizers are not executed by the same thread that collects garbage.
Instead, the GC places each object that is ready for finalization in a queue
and spawns yet another thread to execute all the finalizers. It continues with
its business, removing other garbage from memory. On the next GC cycle,
those objects that have been finalized are removed from memory. Figure 2.2
shows three different GC operations and the difference in memory usage.
Notice that the objects that require finalizers stay in memory for extra cycles.
 
Search WWH ::




Custom Search