tailieunhanh - Praise for C# 2.0: Practical Guide for Programmers 2005 phần 9

Tham khảo tài liệu 'praise for c# : practical guide for programmers 2005 phần 9', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 186 Chapter 9 Resource Disposal Input Output and Threads by the .NET Framework. Responsibility for the disposal of unmanaged resources therefore rests with the object itself and is encapsulated in a destructor as shown here public class ClassWithResources ClassWithResources Release resources III Although the destructor is typically concerned with the release of unmanaged resources it may also release or flag managed resources by setting object references to null. When a destructor is explicitly defined it is translated automatically into a virtual Finalize method public class ClassWithResources virtual void Finalize try Release resources finally baseiFinalize Base class chaining. III The finally clause chains back the disposal of resources to the parent object its parent and so on until remaining resources are released by the root object. Because the invocation of the destructor or Finalize method is triggered by the garbage collector its execution cannot be predicted. In order to ensure the release of resources not managed by the garbage collector the Close or Dispose method inherited from IDisposable can be invoked explicitly. The IDisposable interface given here provides a uniform way to explicitly release resources both managed and unmanaged. interface IDisposable void Dispose Whenever the Dispose method is invoked explicitly the GCiSuppressFinalize should also be called to inform the garbage collector not to invoke the destructor or Finalize method of the object. This avoids the duplicate disposal of managed resources. To achieve this goal two Dispose methods are generally required one with no parameters as inherited from IDisposable and one with a boolean parameter. The following code Resource Disposal 187 skeleton presents a typical strategy to dispose both managed and unmanaged resources without duplicate effort. public class ClassWithResources IDisposable ClassWithResources Initialize resources disposed false ClassWithResources Translated as Finalize .