【发布时间】:2012-06-28 16:38:29
【问题描述】:
我创建了一个循环遍历大量 XML Schema (.xsd) 文件的 PowerShell 脚本,并为每个文件创建一个 .NET XmlSchemaSet 对象,调用 Add() 和 Compile() 为其添加架构,并打印出所有验证错误。
这个脚本可以正常工作,但是某处存在内存泄漏,如果在 100 个文件上运行,它会消耗 GB 的内存。
我基本上在一个循环中做的事情如下:
$schemaSet = new-object -typename System.Xml.Schema.XmlSchemaSet
register-objectevent $schemaSet ValidationEventHandler -Action {
...write-host the event details...
}
$reader = [System.Xml.XmlReader]::Create($schemaFileName)
[void] $schemaSet.Add($null_for_dotnet_string, $reader)
$reader.Close()
$schemaSet.Compile()
(可以在此 gist 中找到重现此问题的完整脚本:https://gist.github.com/3002649。只需运行它,然后在任务管理器或进程资源管理器中观察内存使用量的增加。)
受一些博客文章的启发,我尝试添加
remove-variable reader, schemaSet
我也尝试从Add() 拿起$schema 并做
[void] $schemaSet.RemoveRecursive($schema)
这些似乎有一些效果,但仍然存在泄漏。我假设 XmlSchemaSet 的旧实例仍在使用内存而没有被垃圾收集。
问题:我如何正确地教导垃圾收集器它可以回收上面代码中使用的所有内存?或更笼统地说:我怎样才能用有限的内存来实现我的目标?
【问题讨论】:
标签: powershell memory-leaks garbage-collection xsd xmlschemaset