【发布时间】:2012-12-20 19:05:07
【问题描述】:
我编写了一个启动器实用程序,它使用Timer 上的Directory.GetFiles() 来跟踪开始菜单中的快捷方式。
但是,它存在内存泄漏。我没有做任何奇怪的事情,所以我不明白为什么它会泄漏......我让程序保持打开状态,几天后,它达到了 300mb。我使用 CLR Profiler 试图定位泄漏,它说内存泄漏来自 Directory.GetFiles 和 Directory.GetFileNameWithoutExtension 分配的 String 实例这是我正在使用的代码:
Private Sub tmr_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmr.Tick
IndexStartMenu()
GC.Collect()
End Sub
Private Sub IndexStartMenu()
Dim startMenu As IO.DirectoryInfo
Dim shortcuts() As IO.FileInfo
'Enumerate current user's start menu
startMenu = New IO.DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu))
shortcuts = startMenu.GetFiles("*.lnk", IO.SearchOption.AllDirectories)
For Each lnk As IO.FileInfo In shortcuts
Dim newRow As DataRow = dtApps.NewRow
newRow("Application") = IO.Path.GetFileNameWithoutExtension(lnk.FullName)
newRow("Window") = "Launch"
newRow("Hwnd") = ""
newRow("IsShortcut") = True
newRow("ShortcutPath") = lnk.FullName
dtApps.LoadDataRow(newRow.ItemArray, LoadOption.Upsert)
newRow = Nothing
Next
'Enumerate all users' start menu
startMenu = New IO.DirectoryInfo(allUsersStartMenuPath)
shortcuts = startMenu.GetFiles("*.lnk", IO.SearchOption.AllDirectories)
For Each lnk As IO.FileInfo In shortcuts
Dim newRow As DataRow = dtApps.NewRow
newRow("Application") = IO.Path.GetFileNameWithoutExtension(lnk.FullName)
newRow("Window") = "Launch"
newRow("Hwnd") = ""
newRow("IsShortcut") = True
newRow("ShortcutPath") = lnk.FullName
dtApps.LoadDataRow(newRow.ItemArray, LoadOption.Upsert)
newRow = Nothing
Next
'Trying to fix memory usage
startMenu = Nothing
Array.Clear(shortcuts, 0, shortcuts.Length)
shortcuts = Nothing
End Sub
【问题讨论】:
-
确保部署您的 Release 版本。 vb.net 应用程序的调试版本在没有附加调试器的情况下运行时泄漏。
-
不,没有区别。
-
哇,那几天一晃而过。没有任何方法可以在 17 分钟内看到。
-
大声笑,出于测试目的,我将计时器间隔从 60,000 毫秒更改为 20 毫秒。
-
您检索到的字符串被放入数据表 dtApps 中,该数据表不在 Sub 的范围内。也许那些还在某处被引用?
标签: vb.net memory-leaks