Chú ý rằng trình biên dịch tạo ra một chức năng Vứt bỏ mà các cuộc gọi hệ thống:: GC:: SuppressFinalize. Chức năng này giúp đỡ được cung cấp bởi các FCL để đảm bảo rằng finalizer không được gọi cho một đối tượng. Việc thực hiện Vứt bỏ qua xử lý này SuppressFinalize để các đối tượng chỉ xử lý không hoàn thành. | CHAPTER 11 RELIABLE RESOURCE MANAGEMENT 259 Notice that the compiler generates a Dispose function that calls System GC SuppressFinalize. This helper function is provided by the FCL to ensure that the finalizer is not called for an object. The Dispose implementation passes the this handle to SuppressFinalize so that the object just disposed is not finalized. Calling Dispose and a finalizer on the same object would likely end up in double cleanup and would also negatively impact performance. As you can see in the preceding sample code the compiler overrides System Object Finalize. Instead of calling the finalization function SampleClass SampleClass directly the override of Finalize calls the virtual function Dispose bool . However in contrast to the IDisposable Dispose implementation the finalizer passes false as the argument. Dispose bool is implemented so that it calls the destructor SampleClass SampleClass if true is passed and the finalization function SampleClass SampleClass if the argument is false. This design enables derived classes to implement custom destructors and finalization functions that extend the cleanup logic of the base class. 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 .