The Dispose Pattern—IDisposable

The dispose pattern gives developers an explicit mechanism to release unmanaged resources immediately rather than relying on a GC cycle. This is accomplished by implementing the IDisposable interface.

IDisposable Example

Consider the TCriticalSection class from the previous section. The following is its reworked definition that implements IDisposable:

TCriticalSection = class(TObject, IDisposable)
private
  FSection: TRTLCriticalSection;
  FCSValid: Boolean;
strict protected
    procedure Finalize; override;
public
  constructor Create;
  procedure Dispose;
end;

You should notice that the object now implements the IDisposable interface and its Dispose() procedure. Also, an FCSValid Boolean field will be initialized to False ...

Get Delphi for .NET Developer’s Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.