Library Object Lifespan Questions

JesseW

Active Member
Licensed User
Longtime User
Quick question (which I can't find the answer to): does the .dispose method destroy the object (ie. the spoon of coffee) along with the instance (ie. the cup of coffee?)

Here's what I want to do:

B4X:
'bin is a BinaryFile object
'cry is a Crypto object
Sub Globals
   Dim Data(0) as Byte
   Dim Encrypted(0) as Byte
End Sub

Sub SaveData(DataString)
   Dim Data(StrLength(DataString)) as Byte      'someone said this made a difference??
   Dim Encrypted(StrLength(DataString)) as Byte
   If FileExist("EncryptData.dat") Then _
      FileDel("EncryptedData.dat")   'start with a fresh file
   FileOpen(c1, "EncryptedData.dat", cRandom)
   bin.New1(c1, True)
   Data() = bin.StringToBytes(DataString)
   cry.New1
   Encrypted() = cry.Encrypt(PassPhrase, Data())
   bin.WriteBytes(Encrypted())
   bin.Dispose
   FileClose(c1)
   cry.Dispose      'does this destroy just the instance or does it destroy the object as well???
End Sub

The first time through, this should work as advertised, but what about subsequent times through, in case the SaveData sub is called more than once? Will the bin.New1 and cry.New1 statements still work? I want to avoid memory leaks as well as making sure it works correctly. Thanks in advance... :)

Edit: I'm also curious about lifespans.. If the .Dispose methods in the example are omitted, will the objects/instances be destroyed when the sub is ended, along with the local variables or will they survive? If they survive, what would subsequent .New1 calls do to an instance that's already created, the next time the SaveData sub is called? Thanks again...
 
Last edited:

agraham

Expert
Licensed User
Longtime User
New creates a new instance of a class (object). Dispose removes it from Basic4ppc and makes it available for the .NET Garbage Collector to sweep it up.

Calling New on an object that has already been Newed removes the first instance and creates a new instance with the same name. As no references to the first instance now exist that instance is now a candidate for the Garbage Collector even though it has not explicitly been Disposed.

In general you do not need to use Dispose, the .NET Framework takes care of memory allocation for you. The one exception is Bitmaps. For a discussion of .NET memory management see the "Bitmap memory overview" topic in my http://www.b4x.com/forum/additional-libraries/3171-imagelibex-library.html#post17721
 

JesseW

Active Member
Licensed User
Longtime User
thanks agraham! that was a fantastic explanation. i feel like a pro now :)
 
Top