我有一个我编写的启动器实用程序,用于Directory.GetFiles()
跟踪Timer
开始菜单中的快捷方式。
但是,它有内存泄漏。我没有做任何奇怪的事情,所以我不明白为什么它会泄漏......我让程序保持打开状态,几天后,它达到了 300mb。我使用 CLR Profiler 尝试定位泄漏,它说内存泄漏来自String
分配的实例Directory.GetFiles
,Directory.GetFileNameWithoutExtension
这是我正在使用的代码:
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