[VB.NET] Memory Leak from Object


Deskripsi
    Memory leak always to be enemy of ours (as a programer). it will increasing memory up up up and then slow computers client performance and last think freeze LoL -_- , .NET provide feature GarbageCollector or we called GC to clean unmanaged resource.

Howto
    1. Create class with implements IDisposable
    2. Create sub with name Dispose Implements IDisposable.Dispose
    3.  Add GC.SuppressFinalize(Me), to not execute Finalize sub when dispose the object , normally every object closing always execute Finalize() , if you want to always execute sub Finalize you must not use this method.

example class :

Public Class test
           Implements IDisposable
 
    Public Sub New()
         ' Always executed when object created
         ' you add paramater like another sub
    End Sub

    public sub HelloWorld()
         MessageBox.show("test memory")
    end sub

    Protected Overrides Sub Finalize()
          'Always executed when object destroy
   End Sub

    Sub Dispose() Implements IDisposable.Dispose
           GC.SuppressFinalize(Me) 'not must
    End Sub
end class



in some function or event (for example click)

MessageBox.Show("Current Memory : " & GC.GetTotalMemory(False))
dim obj = new test()
obj.HelloWorld()
MessageBox.Show("Total Memory after add object : " & GC.GetTotalMemory(False))
obj.dispose()
obj = nothing
GC.Collect() ' GC is Garbage Collector
MessageBox.Show("Total memory after object dispose : " & GC.GetTotalMemory(False))

you will know the different every messagebox :D , don't focus the memory value on taskmanager.

Post a Comment

Harap gunakan bahasa yang baik dan sopan, terima kasih