The Dispose Statement

Syntax

$ DisposeStatement = DISPOSE Ident ";"

Description

The Dispose statement in the Fore language is used to solve quite specific problems caused by inability to determine when non-used objects are released. The garbage collector destroys created and unused objects (non-referred). The garbage collector is usually started at system idle time. Therefore, it may take quite a long time between the moment when object links have been zeroed and the actual object destroying. This delay time and the fact that it is non-determined may cause some development problems. 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 finally deleted. Starting the example shows a standard exception "The process cannot access the file because it is being used by another process" in the File.Delete string. It seems that when the Fs variable is set to Null, the only link 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 links, 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 statement is used for this purpose. Define the variable and use the Dispose statement to release the object links and to delete it.

There are several restrictions for this statement:

  1. Use this statement only for system class objects, which are COM objects wrappers. It does not make sense to apply it to custom classes described by application developers.

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

  3. If there are other links to this object, the Dispose statement call will not result in the expected effect. To release the internal COM object, delete all the links to 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