VB.NET Handles clause and MemProfiler

Use this forum for questions on how to use .NET Memory Profiler and how to analyse memory usage.
Post Reply
sparky2708
Posts: 4
Joined: Sat Jan 22, 2011 5:14 am

VB.NET Handles clause and MemProfiler

Post by sparky2708 » Tue Jan 22, 2013 7:51 pm

In an Instance Graph, how do I tell which event handlers are created because of a "Handles XXXEvent clause" on some method AS OPPOSED TO an event handler being created because of "AddHandler XXXEvent, AddressOf SomeDelegate" statement. I can't think of a case where the former would be a memory leak but the latter is most definitely a memory leak (usually indicates someone forgot to do a "RemoveHandler XXXEvent...") and I would like to be informed of the latter case ALWAYS but NOT of the former. How can I accomplist this?

Andreas Suurkuusk
Posts: 1029
Joined: Wed Mar 02, 2005 7:53 pm

Re: VB.NET Handles clause and MemProfiler

Post by Andreas Suurkuusk » Thu Jan 24, 2013 11:21 am

The profiler does not currently indicate which EventHandlers are created using the Handles clause. The Handles clause is translated to an AddHandler clause when the application is compiled. It would be possible for the profiler to identify a Handles EventHandler (e.g. by looking at the allocation call stack), and maybe this is something we will implement in the future.

Still, I'm not sure how useful this information would be.The Handles clause is often used to subscribe to events in child instances (e.g. child controls of a form), where all involved instances have the same life-time. In this case the Handles clause will most likely not cause a memory leak, but neither would a forgotten RemoveHandler call. On the other hand, the Handles clause can also be used to handle events from long-living instances. For example, see the code below. In this case you would get a memory leak unless the event instance is cleared.

Code: Select all

Public Class EventConsumer
    WithEvents eventInstance As EventClass

    Public Sub InitEventInstance()
        eventInstance = EventClass.Instance
    End Sub

    Private Sub Ctrl_Changed(sender As Object, e As EventArgs) Handles eventInstance.TestEvent
        MessageBox.Show("Test")
    End Sub
End Class

Public Class EventClass
    Event TestEvent As EventHandler

    Public Shared Instance As EventClass = New EventClass
End Class
The automatic memory analyzer in the profiler will give you information about instances that are only kept alive through an EventHandler (or a delegate). This is a better indication of a memory leak than whether the EventHandler was created using AddHandler or Handles.
Best regards,

Andreas Suurkuusk
SciTech Software AB

Post Reply

Who is online

Users browsing this forum: No registered users and 39 guests