An easy and safe technique for preventing circular references  in Visual Basic 6

Avoiding a circular reference in VB6 (VB 6, classic VB, VB classic)

How to prevent a circular reference in VB6

How to avoid a circular reference in VB6

by VT Software

 

Summary

A weak reference (or uncounted reference) to an object is one that does not prevent the object from terminating.

Imagine for a moment that Microsoft had designed VB6 with a built-in WeakReference type, that every object had a built-in property that returned a weak reference to the object, and that a weak reference could easily be converted back to a normal reference. Avoiding circular references would then be very easy. You would just store weak references to parent objects in the child objects.

Imagine no more! With a few lines of code you can customise any VB6 project to achieve all this. Here's how:

Step by step

1    Download WeakReference.cls and add it to your project, or compile it in a DLL used by all your projects.

2    Add a WeakReference property to your root class by copying and pasting the following code into your root class module.  It does not need any modification:

'Weak reference to this object (module level variable declaration)
Private
mWeakReference As WeakReference

Friend Property Get WeakReference() As WeakReference
    'Return a weak reference to this object
    Set
WeakReference = mWeakReference
End Property

Private Sub Class_Initialize()
    'Create a weak reference to this object
    Set
mWeakReference = New WeakReference
    mWeakReference.Initialize Me
End Sub


Private Sub Class_Terminate()
   
'Reset the weak reference. If this method is not called and this
    'object is accessed after it has terminated, VB will crash.

    mWeakReference.Destroy
End Sub

3    Add a Parent property to dependent classes by copying and pasting the following code into any dependent class module (where Root is the name of your root class):

'Weak reference to root object (module level variable declaration)
Private
mwrRoot As WeakReference

Public Property Get Parent() As Root
   
'Convert weak reference back to a normal reference
    Set
Parent = mwrRoot.Target
End Property

Friend Property Set Parent(NewValue As Root)
   
'Store a weak reference to the root object
    Set
mwrRoot = NewValue.WeakReference
End Property

We would be pleased to find out how you get on using this code. Please send an email.

The downloads and code referred to on this site are provided free of charge by VT Software Limited.  No responsibility is accepted for any problems or loss arising from their use.  Support cannot be provided.

 

 

 

 

Hit Counter