首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >内存泄漏Directory.GetFiles() VB.NET

内存泄漏Directory.GetFiles() VB.NET
EN

Stack Overflow用户
提问于 2012-12-21 03:05:07
回答 1查看 918关注 0票数 0

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

然而,它有一个内存泄漏。我没有做任何奇怪的事,所以我不明白为什么它会泄露...我让程序开着,几天后,它就变成300mb了。我使用CLR事件探查器试图定位泄漏,它显示内存泄漏来自Directory.GetFilesDirectory.GetFileNameWithoutExtension分配的String实例。下面是我使用的代码:

代码语言:javascript
运行
复制
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
EN

回答 1

Stack Overflow用户

发布于 2012-12-21 09:02:54

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13978798

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档