我有一个启动器实用程序,我在Directory.GetFiles()
上使用Timer
来跟踪开始菜单中的快捷方式。
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
答案 0 :(得分:1)
根据您发布的方法,定时器是否只会触发每个间隔并重复添加这些目录的内容?如果dtApps是一个作用于该类的DataTable字段,该字段在应用程序的持续时间内持续存在,那么您只需将这些行重复添加到DataTable中,从而使其增长。它不是内存泄漏,而是一个自然事件。检查dtApps的行数。我的猜测是你打算只添加新行。
此外,您可以改进上述解决方案,并且无需使用FileSystemWatcher基于计时器轮询这两个目录。当文件系统发生更改时,FileSystemWatcher将通过触发事件来通知您。