我有一个我写的启动器实用程序,它在Timer上使用Directory.GetFiles()来跟踪开始菜单中的快捷方式。
然而,它有一个内存泄漏。我没有做任何奇怪的事,所以我不明白为什么它会泄露...我让程序开着,几天后,它就变成300mb了。我使用CLR事件探查器试图定位泄漏,它显示内存泄漏来自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发布于 2012-12-21 09:02:54
根据您发布的方法,计时器不是每隔一段时间就触发一次,然后重复添加这些目录的内容吗?如果dtApps是一个DataTable字段,它的作用域是在应用程序期间持续存在的类,那么您只是重复地将行添加到DataTable中,从而导致它增长。这不是内存泄漏,而是一个自然事件。检查dtApps的行数。我的猜测是,您只打算添加新行。
此外,您还可以改进上面的解决方案,并通过使用FileSystemWatcher消除基于计时器轮询两个目录的需要。当文件系统发生更改时,FileSystemWatcher将通过触发事件来通知您。
https://stackoverflow.com/questions/13978798
复制相似问题