Article number: KB000004
Related blocks:
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:
The statement can be efficiently applied only to the objects of system classes that are used as wrappers for COM objects. It does not make sense to apply it to custom classes described by application developers.
After executing the Dispose statement the link to wrapper object is not cleared, and the Null value is not assigned. The link 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 exception.
If there are other links to this object, calling the Dispose statement does not give the expected effect. To release an internal COM object, delete all links 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 file
Finally
Dispose Fs;
File.Delete(FileName);
End Try;
End Sub UserProc;
See also: