In this article:

General Information

Description

Example

Using the Dispose Statement

Article number: KB000004

General Information

Related blocks:

Description

The Dispose statement in the Fore language is used to solve rather specific problems related to undetermined time of objects release. The objects that are not in use (there are no links to these objects) are deleted by the garbage collector. As a rule, garbage collector is started at the system idle times. Therefore, rather a long time may pass between deleting links to an object and actual deleting of this object. This period and especially its indefiniteness may cause problems for developers. See the following example:

Sub UserProc;
Var
    FileName: String;
    Fs: FileStream;
Begin
    FileName := Path.GetTempFileName;
    Fs := New FileStream.Create(FileName, FileOpenMode.Create, FileShare.Exclusive);
    Try
        // Operations with file
    Finally
        Fs := Null;
        File.Delete(FileName);
    End Try;
End Sub UserProc;

In this example a temporary file is created, then some operations are executed with this file and the file is deleted. When the example is started, the File.Delete string throws the standard exception: The process cannot access the file because it is being used by another process. Some developers assume that after the Fs variable is set to Null, the only link to the File Stream object is deleted and the file is closed. Actually, this is not so, as the File Stream object is stored in the memory till the garbage collector is started. As a result, the file is not released and cannot not be deleted.

Thus, we need a method for determined release of links to resources. The Dispose statement is used for this purpose. If you need to release a link to an object using the determined method, use this statement and specify the required variable.

There is a number of restrictions when using the statement:

Example

Correct release of unused objects:

Sub UserProc;
Var
    FileName: String;
    Fs: FileStream;
Begin
    FileName := Path.GetTempFileName;
    Fs := New FileStream.Create(FileName, FileOpenMode.Create, FileShare.Exclusive);
    Try
        // Operations with file
    Finally
        Dispose Fs;
        File.Delete(FileName);
    End Try;
End Sub UserProc;

See also:

Developers Knowledge Base