0

我有一个我编写的启动器实用程序,用于Directory.GetFiles()跟踪Timer开始菜单中的快捷方式。

但是,它有内存泄漏。我没有做任何奇怪的事情,所以我不明白为什么它会泄漏......我让程序保持打开状态,几天后,它达到了 300mb。我使用 CLR Profiler 尝试定位泄漏,它说内存泄漏来自String分配的实例Directory.GetFilesDirectory.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
4

1 回答 1

1

根据您发布的方法,计时器不会每隔一段时间触发一次并重复添加这些目录的内容吗?如果 dtApps 是一个范围为在应用程序期间持续存在的类的 DataTable 字段,那么您只是重复地将行添加到 DataTable 导致它增长。这不是内存泄漏,而是自然事件。检查 dtApp 的行数。我的猜测是您打算只添加新行。

此外,您可以改进上述解决方案,并通过使用FileSystemWatcher消除基于计时器轮询两个目录的需要。当文件系统发生更改时,FileSystemWatcher 将通过触发事件来通知您。

于 2012-12-21T01:02:54.247 回答