The Dispose Statement

Syntax

$ DisposeStatement = DISPOSE Ident ";"

Description

The Dispose statement in the Fore language is used to solve quite a narrow range of problems with object release non-determined time. The garbage collector destroys created and unused objects. The garbage collector is usually started in system downtime. Thus, it may take quite a long time between the moment when object references have been zeroed and the actual object destroying. This delay time and the fact that it is non-determined may cause some problems during the development. For example:

Sub Main;

Var

FileName: String;

Fs: FileStream;

Begin

FileName := Path.GetTempFileName;

Fs := New FileStream.Create(FileName, FileOpenMode.Create, FileShare.Exclusive);

Try

// Do something

Finally

Fs := Null;

File.Delete(FileName);

End Try;

End Sub Main;

In this example a temporary file is created, processed, and (at the end) deleted. Starting the example shows a standard exception "The process cannot access the file, because the file is in use by another process" in the File.Delete string. It seams that, when the Null value is assigned to the Fs variable, the only reference to the "file stream" object will be deleted and the file will be closed. Actually, it is not; despite the fact that there are no references, the "file stream" object remains in memory until the next garbage collection. As a result, the file is not released and cannot not be deleted.

Thus, a resource link release mechanism is required. The Dispose operator is used for this purpose. Define the variable and use the Dispose operator to release determinedly the object reference and to delete it.

There are several restrictions for this operator:

  1. Use this operator only for system class objects, which are the COM objects shells. Applying it to custom classes described by application developers makes no sense.

  2. After the Dispose operator is executed, the reference to the shell-object is not cleaned and a variable, containing the reference, is not set to Null. The reference to the system COM object is cleaned, and this allows the object to be deleted and resources to be released. After the Dispose operator is executed, any object call will throw exception.

  3. If there are other references to this object, the Dispose operator call will not result in the the expected effect. To release the internal COM object, delete all the references on this object.

The correct example looks as follows:

Sub Main;

Var

FileName: String;

Fs: FileStream;

Begin

FileName := Path.GetTempFileName;

Fs := New FileStream.Create(FileName, FileOpenMode.Create, FileShare.Exclusive);

Try

// Do something

Finally

Dispose Fs;

File.Delete(FileName);

End Try;

End Sub Main;

See also:

Statements