人们不断地谈论由于未释放的事件侦听器而发生的内存泄漏。我认为这是一个非常重要的问题。非常严肃,非常重要……如果它真的存在的话。
我已经尝试自己重现这个问题,但我所有的尝试都失败了:我就是不能让我的应用程序泄漏内存:(虽然听起来不错,但我仍然担心:也许我错过了一些东西。
那么也许有人可以提供一个非常简单的导致内存泄漏的源代码示例?
我创建了一个小型 VB.NET 应用程序作为演示:它包含一个 Windows 窗体和一个类。
Windows 窗体:它有一个集合对象(名为“c”)和两个按钮:一个用于将 10 个项目添加到集合中,另一个用于清除集合:
Public Class Form1
Dim c As New Collection
Private Sub btnAddItem_Click(sender As System.Object, e As System.EventArgs) Handles btnAddItem.Click
For i As Integer = 1 To 10
Dim m As New MyType
c.Add(m)
Next
Me.Text = c.Count
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
For Each item As MyType In c
item.Dispose()
Next
c.Clear()
Me.Text = c.Count
End Sub
End Class
MyType 类:它有很大的 m_Image 对象,它很大,所以你可以看到你的内存真的被 MyType 实例占用了:)
Imports System.Drawing
Public Class MyType
Implements IDisposable
Private m_Image As Bitmap
Public Sub New()
AddHandler Application.Idle, AddressOf Application_Idle
m_Image = New Bitmap(1024, 1024)
End Sub
Private Sub Application_Idle(sender As Object, e As EventArgs)
End Sub
#Region "IDisposable Support"
Private disposedValue As Boolean
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
m_Image.Dispose()
End If
End If
Me.disposedValue = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class