Memory leak when opening XPS document, how to workaround or avoid?


  • The following code snippet illustrates a memory leak when opening XPS files. If you run it and watch the task manager, it will grow and not release memory until the app exits.

    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.WriteLine("Start - {0}", GC.GetTotalMemory(True))
            For LoopCount As Integer = 1 To NumberOfLoops

                Console.CursorLeft = 0
                Console.Write("Loop {0}    ", 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
            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).")

        End Sub

    End Module

    The reason it loops a thousand times is because my code processes lots of files and leaks memory quickly forcing an OutOfMemoryException. Forcing Garbage Collection does not work (I suspect it is an unmanaged chunk of memory in the XPS internals).

    The code was originally in another thread and class but has been simplified to this.

    Any help greatly appreciated.


    Monday, October 20, 2008 2:53 PM

All replies

  • I had the same issue.  I'm creating 10s of 1000's of XPS docs on a 64 bit machine and ended up with a memory footprint of about 4gb.  The issue is with the FixedDocumentSequence.  If you get a page off the FixedDocumentSequence paginator, you'll need to case the page to a FixedPage and call the UpdateLayout method on it.  THis causes the memory to get released.  Not sure why,  but it works.

    See the following post for more info:

    Friday, August 28, 2009 4:33 PM
  • Ironic eh? I wrote that answer :)
    Monday, October 05, 2009 9:05 PM
  • I seem to still be leaking memory even with the fix?
    Monday, October 12, 2009 7:54 PM