以下代碼片段說明打開XPS文件時的內存泄漏。如果您運行它並觀察任務管理器,它將會增長並且不會釋放內存,直到應用程序退出。在.Net中打開XPS文檔導致內存泄漏
'******控制檯應用程序BEGINS。
Module Main
Const DefaultTestFilePath As String = "D:\Test.xps"
Const DefaultLoopRuns As Integer = 1000
Public Sub Main(ByVal Args As String())
Dim PathToTestXps As String = DefaultTestFilePath
Dim NumberOfLoops As Integer = DefaultLoopRuns
If (Args.Count >= 1) Then PathToTestXps = Args(0)
If (Args.Count >= 2) Then NumberOfLoops = CInt(Args(1))
Console.Clear()
Console.WriteLine("Start - {0}", GC.GetTotalMemory(True))
For LoopCount As Integer = 1 To NumberOfLoops
Console.CursorLeft = 0
Console.Write("Loop {0:d5}", LoopCount)
' The more complex the XPS document and the more loops, the more memory is lost.
Using XPSItem As New Windows.Xps.Packaging.XpsDocument(PathToTestXps, System.IO.FileAccess.Read)
Dim FixedDocSequence As Windows.Documents.FixedDocumentSequence
' This line leaks a chunk of memory each time, when commented out it does not.
FixedDocSequence = XPSItem.GetFixedDocumentSequence
End Using
Next
Console.WriteLine()
GC.Collect() ' This line has no effect, I think the memory that has leaked is unmanaged (C++ XPS internals).
Console.WriteLine("Complete - {0}", GC.GetTotalMemory(True))
Console.WriteLine("Loop complete but memory not released, will release when app exits (press a key to exit).")
Console.ReadKey()
End Sub
End Module
'****** Console application ENDS。
循環一千次的原因是因爲我的代碼很快處理大量文件並快速泄漏內存,強制執行OutOfMemoryException。強制垃圾收集不起作用(我懷疑它是XPS內部的非託管塊內存)。
該代碼原本是在另一個線程和類,但已簡化爲此。
任何幫助非常感謝。
瑞安
任何證明這是一個真正的錯誤?它是否被報告,以及repro步驟? – Will 2009-03-30 21:33:30
證明是在布丁中,運行它並查看(評論上面的DirectCast,你會得到一個泄漏)。我沒有提出MS Connect,但與MS社交(http://social.msdn.microsoft.com/Forums/en-US/windowsxps/thread/e31edefa-b07e-450d-8ab8-5a171ee8d4c1/?ppud= 4)。 – 2009-03-31 13:47:36