Quantcast
Viewing all articles
Browse latest Browse all 2

Answer by Erik A for Class_Terminate not firing on object from form

Access doesn't gracefully clean up the form object when you close a form.

That means: if an object has open references to a form, the form object persists. It only can get removed by the garbage collector if there are no references to it.

The first version of the form was creating a memory leak: the form object Form_Form1 had a reference to Class1 (through the MyClass1 variable), Class1 had a reference to the form object through the theForm variable. This caused a reference loop. The terminate handler didn't fire because the class never terminated, it remained in memory indefinitely, and closing and reopening the form just opened up a new instance of the class.

The second version caused a problem: while the reference loop was broken, references to Form1 were released first (because there still was a reference to Class1 on Form1), causing the garbage collector to clean that up, then references to Class1 were released and the garbage collector tried to clean up Class1, including the textbox object SomeTextbox, causing Access to hard-crash since the form object was already cleaned up and the textbox object was invalid.

The solution is to break the reference loop by removing all references to Class1 first. This doesn't cause crashes.

Private Sub Form_Unload(Cancel As Integer)    Set myClass1 = NothingEnd Sub

This causes the garbage collector to clean up the Class1 instance first, releasing references to Text0, then cleans up the form objects because no-one has open references to that.


Viewing all articles
Browse latest Browse all 2

Trending Articles