我创建了一个 PowerShell 脚本,该脚本循环遍历大量 XML 架构 (.xsd) 文件,并为每个文件创建一个 .NETXmlSchemaSet对象、调用Add() and Compile()向其中添加架构,并打印出所有验证错误。
该脚本工作正常,但某处存在内存泄漏,导致如果在数百个文件上运行,则会消耗千兆字节的内存。
我基本上在循环中执行的操作如下:
$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()
(可以在以下要点中找到重现此问题的完整脚本:https://gist.github.com/3002649。只需运行它,然后在任务管理器或进程资源管理器中观察内存使用量的增加。)
受到一些博客文章的启发,我尝试添加
remove-variable reader, schemaSet
我也尝试拿起$schema
from Add()
和做
[void] $schemaSet.RemoveRecursive($schema)
这些看似有一定效果,但还是有漏水的情况。我假设较旧的实例XmlSchemaSet
仍在使用内存而没有被垃圾收集。
问题:我如何正确地告诉垃圾收集器它可以回收上面代码中使用的所有内存?或者更一般地说:我如何利用有限的内存来实现我的目标?