Article number: KB000004
Related blocks:
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:
The operator can be efficiently applied only to the objects of system classes that are used as "wrappers" for COM objects. Applying it to custom classes described by application developers makes no sense.
After executing the Dispose operator the reference to wrapper object is not cleared and the Null value is not assigned. The reference to the system COM object is cleared, which makes it possible to delete this object and release the resources. After calling the Dispose statement all attempts to access the object lead to exceptional situation.
If there are other references to this object then calling the Dispose operator does not give the expected effect. To release an internal COM object you need to delete all references to this object.
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: