Information Technology Reference
In-Depth Information
Calling the Finalizer
Unlike the C++ destructor, a C# finalizer is not called immediately when an instance goes out
of scope. In fact, there is no way of knowing when the finalizer will be called. Furthermore, as
mentioned, you cannot explicitly call a finalizer. If your code needs one, you just provide it for
the system, which will call it at some point before the object is destroyed.
If your code contains unmanaged resources that should be released in a timely manner,
you should not leave that for the finalizer, since there is no guarantee that the finalizer will run
anytime soon. Instead, you should adopt the convention of encapsulating the cleanup code for
these resources in a void, parameterless method. By convention, you should call it Dispose .
When you're done with the resources and want them released, call Dispose . Notice that
you need to invoke Dispose —it is not the finalizer, and the system will not call it for you
automatically.
Some guidelines for your Dispose method are the following:
Implement the code in Dispose in such a way that it is all right if the method is called
more than once. It should not cause an exception to be raised, and it should not do any
additional work on subsequent calls.
￿
Don't assume that Dispose will get called. Make sure that the finalizer will release the
resources if, for some reason, Dispose isn't called.
￿
Comparison of Constructors and Finalizers
Table 6-3 provides a summary of when constructors and finalizers are called.
Table 6-3. Constructors and Finalizers
When and How Often Called
Instance
Constructor
Called once on the creation of each new instance of the class.
Finalizer
Called for each instance of the class, at some point after the program
flow can no longer access the instance.
Static
Constructor
Called only once—either before the first access of any static member
of the class, or before any instances of the class are created—which-
ever is first.
Finalizer
Does not exist—finalizers only work on instances.
Search WWH ::




Custom Search