You create a Microsoft Visual Basic application in Microsoft Visual Studio 2005 or in Visual Studio 2008.
The Visual Basic application contains a class.
The class contains an event.
The Visual Basic application creates an instance of the class.
You compile the Visual Basic application in debug mode.
In this scenario, when you run the Visual Basic application, memory usage increases.
Note You are more likely to notice this behavior when the following conditions are true:
The Visual Basic application runs continuously for a long time.
The Visual Basic application creates many instances of the class that contains an event. If instances are created enough times, the application will eventually fail with an OutOfMemoryException or "out of memory" error. For example, the Visual Basic application contains a loop that creates multiple instances of the class.
This issue occurs because the Edit and Continue debugging feature in Visual Studio 2005 or in Visual Studio 2008 maintains a list of weak references to objects that have been created. If the object that has been created is a class that contains an event, these weak references are maintained for the duration of the program. This behavior increases memory usage.
To resolve this issue, use either of the following methods.
Method 1: Restart the Visual Basic application
You can restart the Visual Basic application. When you do this, the memory is freed.
Method 2: Compile the Visual Basic application in release mode
You can compile the Visual Basic application in release mode. When you run a Visual Basic application that was compiled in release mode, memory usage does not increase when you create an instance of a class that contains an event.
Steps to reproduce the issue
Start Visual Studio 2005 or Visual Studio 2008.
On the File menu, point to New, and then click Project.
Under Project types, click Visual Basic. If you cannot see the Visual Basic project type, expand Other Languages, and then click Visual Basic.
Under Templates, click Console Application.
Type a project name, and then click OK.
Replace all the code in the Code window with the following code.
Module Module1 Private Sub CreateClassWithEvent() Dim TestClass As New CLeak End Sub Sub Main() ' This loop infinitely creates a class that contains an event. While True CreateClassWithEvent() System.GC.Collect() System.GC.WaitForPendingFinalizers() Threading.Thread.Sleep(50) End While End SubEnd ModuleClass CLeak Event myEvent()End Class