What Should a Finalizer Clean Up

There is an important difference between the cleanup work done during normal object destruction and during finalization. When an object is finalized, it should clean up only native resources. During finalization, you are not allowed to call another finalizable .NET object, because the called object could be finalized already. The order of finalization calls is undetermined. (There is one exception to this rule, which I will discuss later in this chapter.)

The wrapper class shown in the following code has two fields: a native handle (hxyz) and a tracking reference to a finalizable object (memberObj). Notice that the destructor cleans up the managed resource and the native resource (it deletes memberObj and calls XYZDisconnect). In contrast to the destructor, the finalization function cleans up only the native resource.

public ref class XYZConnection {

HXYZ hxyz;

AFinalizableObjectA memberObj; public: XYZConnection()

~XYZConnection() {

// cleanup managed resources: dispose member variables here delete memberObj; memberObj = nullptr;

finally {

// cleanup native resources even if member variables could not be disposed if (hxyz) {

!XYZConnection()

// do not call any finalizable

// they are probably finalized if (hxyz)

::XYZDisconnect(hxyz);

Apart from some really rare exceptions, you should implement finalization logic only in classes that wrap native resources. A class that implements finalization logic should always implement a destructor for normal cleanup, too. Often the destructor is implemented by simply forwarding the call to the finalization function.

When implementing finalization logic, do not make assumptions about the thread that performs the finalization. The current CLR implementation uses a special thread that is dedicated to calling the finalizers. However, the CLI does not specify how finalization should be implemented with respect to threads. In future versions, there may be more than one finalizer thread to ensure that finalization does not end up in a bottleneck.

Was this article helpful?

0 0

Post a comment