Disposing Object in VB.Net

How to dispose objects created in a Sub or functions like this:

Public sub MyXTree()
Dim mynode as treeview

Dim xString as string

'Do some thing with xtree
for mynode in Treeview.Node
.....
......
xstring = mynode.text
next

Mynode=Nothing '? is this the right method of disposing
xString = Nothing '?is this the right method of disposing?
End Sub

'In VB6 by declaring nothing we can dispose off the object provided the object is not called immediately. Otherwise same reference of the object will be created with garbage value.
'I want to know how to dispose object declared inside a sub or function after the work is done.
'Friends if u know please Write to me.

Comments


  • Setting an Object to Nothing is one way of telling the system that it is no longer needed. (If it goes out of scope, it will automatically be marked up for destruction.) In either case, the object will be destroyed by the .Net Framework .

    Setting an object to Nothing in VB.Net doesn't have quite the same effect as doing this in VB6. In .Net the Nothing keyword tells the system that the object can be freed up (as opposed to VB Classic where it more or less instantly freed up the memory and resources).

    Note that in .Net the object is not actually released from memory until the Garbage Collector has kicked in.

    You probably are already aware that in the example you give:
    [code]
    Dim mynode as treeview
    [/code]
    at this stage the mynode variable is Nothing. It has to be initialized with the New keyword before it actually represents an object. (Just thought I would mention it in passing)

    Anyway, see if this code helpts to clarify it:
    (I've assumed that you meant to create MyNode as a TreeNode, not a TreeView as you have posted (?).
    [code]
    ' Declare a variable for a TreeNode
    Dim MyNode As TreeNode
    ShowState(MyNode) ' State?

    ' Instantiate it
    MyNode = New TreeNode
    ShowState(MyNode) ' State?

    ' Set it to Nothing
    MyNode = Nothing
    ShowState(MyNode) ' State?

    [/code]
    The above is normally all you need to do to dereference an object and wait for it to be garbage collected. If for some reason you have to be sure that it really has been completedly removed from memory, then you can force the Garbage Collection to collect immediately with:
    [code]

    System.GC.Collect()
    [/code]
    Note that forcing the GC to kick in too often is very inefficient and so should only be used with care.



Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion