In this article:

General Information

Description

Example

Using the Dispose Operator

Article number: KB000004

General Information

Related blocks:

Description

The Dispose operator 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 references to these objects)are deleted by the garbage collector. As a rule, the garbage collector is started at the system downtime. Thus, rather a long time may pass between deleting references 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 a file
    Finally
        Fs := Null;
        File.Delete(FileName);
    End Try;
End Sub UserProc;

In this example, a temporary file is created, then some operations are performed on this file and the file is deleted. When the example is launched the following exception occurs in the string File.Delete : The process cannot access file as the file is used by another process. Some developers think that after the Fs variable is set to Null, the only reference 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 launched. As a result, file is not released and cannot not be deleted.

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

A number of restrictions limits using the operator:

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 a file
    Finally
        Dispose Fs;
        File.Delete(FileName);
    End Try;
End Sub UserProc;

See also:

Developers Knowledge Base