11.3 Garbage Coltection

Top  Previous  Next

prev

next

 

11.3 Garbage Collection

In VBA, an object was destroyed when its last reference was removed. This approach was implemented through reference counting. So it was always clear when an object would be terminated, triggering a call to its Class_Terminate event. In VSTO, however, reference counting has been replaced with so-called garbage collection: At certain times, the system will run through all objects looking for those that no longer have any references. Those objects are then terminated — the garbage collected by triggering the Class_Finalize event.

In other words, we don't know exactly when an object will really be destroyed in VSTO. Once all references have been eliminated, objects will just hang around in memory until the garbage collection performs a cleanup. You can take decisions into your own hand by using the class Dispose() hethod.

What is the advantage of garbage collection? We won't go into all its details except for mentioning the fact that it eliminates circular reference issues found with reference counting. If two objects have references to each other and there are no references to either object left, the garbage collector will discover and terminate them, whereas VBA would have left them in memory forever. Another advantage is that garbage collection takes place when the application is otherwise idle, thus not interfering with overall performance.

Let's say we want to create a class that handles bank transactions for a bank account. What we would need is a Class plus a Form that uses this new Class. We could do much more — for instance, creating a collection of bank accounts, and then saving to disk the information for all accounts (as we did in 9.2). But this time, we will leave that part up to you.

 

prev

next