Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marnix/3293302 to your computer and use it in GitHub Desktop.
Save marnix/3293302 to your computer and use it in GitHub Desktop.
Following gist https://gist.github.com/3002649, this fixes the leak following a MSFT suggestion but introduces event loss
function cleanup() {
write-host "Cleaning up..."
remove-item $schemaFile
break
}
trap {
cleanup
}
# The following was stolen from http://powershellquiz.com/post/10429186577/a4-one-bit-of-difference
Add-Type -Language CSharp -TypeDefinition @'
public class NullString {
public override string ToString() {
return null;
}
}
'@
$null_for_dotnet_string = New-Object -TypeName NullString;
$TEST_SCHEMA = @'
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:x">
<element name="a" type="string"/>
<element name="b" type="string"/>
<element name="c" type="string"/>
<element name="d" type="string"/>
<element name="e" type="string"/>
<element name="f" type="string"/>
<element name="A" type="x:string"/>
<element name="B" type="string"/>
<element name="C" type="string"/>
<element name="D" type="string"/>
<element name="E" type="string"/>
<element name="F" type="string"/>
</schema>
'@
$schemaFileName = [System.IO.Path]::GetTempFileName()
$TEST_SCHEMA > $schemaFileName
$count = 0
$N = 1000
1..$N |% {
$schemaSet = new-object -typename System.Xml.Schema.XmlSchemaSet
$xyzzy = register-objectevent -SourceIdentifier XYZZY $schemaSet ValidationEventHandler -MessageData $schemaFileName -Action {
$a = $args[1]
$e = $a.Exception
$topLevelFileName = $event.MessageData
$GLOBAL:count += 1
write-host "#$GLOBAL:count $($topLevelFileName): $($a.Severity) in $($e.SourceUri) at line $($e.LineNumber) column $($e.LinePosition): $($e.Message)"
}
try {
$reader = [System.Xml.XmlReader]::Create($schemaFileName)
# Passing $null to a .NET method which expects a string
# doesn't work: PowerShell passes an empty string instead,
# which has a different (and incorrect) meaning for Add().
[void] $schemaSet.Add($null_for_dotnet_string, $reader)
# The following is an attempt to prevent events from getting lost,
# based on a MSFT suggestion--but that doesn't work.
while ($reader.Read()) {
}
$reader.Close()
$schemaSet.Compile()
} catch {
write-host "$($schemaFileName): Exception: $_"
}
# The following works around a memory leak bug in the
# PowerShell/.NET interaction. But it introduces the
# problem that validation events get lost.
Unregister-Event XYZZY
Remove-Job $xyzzy -Force
}
write-host
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment