C#读取XPS导致内存泄漏

时间:2018-07-22 08:34:26

标签: c# memory-leaks

我有一个简单的程序,仅读取XPS文件,我已阅读以下帖子,它确实解决了部分问题。
Opening XPS document in .Net causes a memory leak

class Program
{
    static int intCounter = 0;
    static object _intLock = new object();

    static int getInt()
    {
        lock (_intLock)
        {
            return intCounter++;
        }
    }

    static void Main(string[] args)
    {

        Console.ReadLine();

        for (int i = 0; i < 100; i++)
        {

            Thread t = new Thread(() =>
            {
                var ogXps = File.ReadAllBytes(@"C:\Users\Nathan\Desktop\Objective.xps");
                readXps(ogXps);
                Console.WriteLine(getInt().ToString());
            });
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
            Thread.Sleep(50);
        }
        Console.ReadLine();
    }


    static void readXps(byte[] originalXPS)
    {
        try
        {

            MemoryStream inputStream = new MemoryStream(originalXPS);
            string memoryStreamUri = "memorystream://" + Path.GetFileName(Guid.NewGuid().ToString() + ".xps");
            Uri packageUri = new Uri(memoryStreamUri);
            Package oldPackage = Package.Open(inputStream);
            PackageStore.AddPackage(packageUri, oldPackage);
            XpsDocument xpsOld = new XpsDocument(oldPackage, CompressionOption.Normal, memoryStreamUri);
            FixedDocumentSequence seqOld = xpsOld.GetFixedDocumentSequence();


            //The following did solve some of the memory issue
            //-----------------------------------------------
            var docPager = seqOld.DocumentPaginator;
            docPager.ComputePageCount();
            for (int i = 0; i < docPager.PageCount; i++)
            {
                FixedPage fp = docPager.GetPage(i).Visual as FixedPage;
                fp.UpdateLayout();
            }
            seqOld = null;
            //-----------------------------------------------


            xpsOld.Close();
            oldPackage.Close();
            oldPackage = null;
            inputStream.Close();
            inputStream.Dispose();
            inputStream = null;
            PackageStore.RemovePackage(packageUri);
        }
        catch (Exception e)
        {

        }
    }
}

^程序将读取XPS文件一百次 Before apply the fix ^在应用此修复程序之前

After the fix ^修复后

因此,该帖子中建议的修复程序确实消除了一些对象,但是我发现内存中仍然存在诸如DispatcherContextLayoutManagerMediaContext之类的对象,它们的数量完全相同100,这是正常现象还是内存泄漏?我该如何解决?谢谢。

2018年7月25日更新
添加行Dispatcher.CurrentDispatcher.InvokeShutdown();确实摆脱了DispatcherContextLayoutManagerMediaContext对象,不知道这是否是理想的修复方法。

1 个答案:

答案 0 :(得分:1)

似乎剩下的那些类来自XPSDocument,实现了IDisposable,但您没有调用它们。还有更多的类实现相同的接口,并且根据经验,将它们包装在using语句中,以确保可以调用它们的Dispose方法或调用它们的方法。 Dispose用自己的方式。

readXps方法的改进版本将如下所示:

static void readXps(byte[] originalXPS)
{
    try
    {
        using (MemoryStream inputStream = new MemoryStream(originalXPS))
        {
            string memoryStreamUri = "memorystream://" + Path.GetFileName(Guid.NewGuid().ToString() + ".xps");
            Uri packageUri = new Uri(memoryStreamUri);
            using(Package oldPackage = Package.Open(inputStream))
            {
                PackageStore.AddPackage(packageUri, oldPackage);
                using(XpsDocument xpsOld = new XpsDocument(oldPackage, CompressionOption.Normal, memoryStreamUri))
                {
                    FixedDocumentSequence seqOld = xpsOld.GetFixedDocumentSequence();

                    //The following did solve some of the memory issue
                    //-----------------------------------------------
                    var docPager = seqOld.DocumentPaginator;
                    docPager.ComputePageCount();
                    for (int i = 0; i < docPager.PageCount; i++)
                    {
                        FixedPage fp = docPager.GetPage(i).Visual as FixedPage;
                        fp.UpdateLayout();
                    }
                    seqOld = null;
                    //-----------------------------------------------           
                } // disposes XpsDocument
            } // dispose Package
            PackageStore.RemovePackage(packageUri);
         } // dispose MemoryStream
    }
    catch (Exception e)
    {
        // really do something here, at least:
        Debug.WriteLine(e);
    }
}

这至少应该清理大多数对象。我不确定您是否会在分析中看到效果,因为这取决于在分析过程中是否实际收集了对象。对调试版本进行性能分析可能会产生意外的结果。

由于这些对象实例的其余部分似乎都绑定到System.Windows.Threading.Dispatcher,因此我建议您尝试保留对线程的引用(但此时您可能考虑研究Tasks),并且一次线程完成后,在分派器上调用静态ExitAllFrames

您的主要方法将如下所示:

Console.ReadLine();

Thread[] all = new Thread[100];
for (int i = 0; i < all.Length; i++)
{
    var t = new Thread(() =>
    {
        var ogXps = File.ReadAllBytes(@"C:\Users\Nathan\Desktop\Objective.xps");
        readXps(ogXps);
        Console.WriteLine(getInt().ToString());
    });
    t.SetApartmentState(ApartmentState.STA);
    t.Start();
    all[i] = t; // keep reference
    Thread.Sleep(50);
}
foreach(var t in all) t.Join(); // https://stackoverflow.com/questions/263116/c-waiting-for-all-threads-to-complete
all = null; // meh
Dispatcher.ExitAllFrames(); // https://stackoverflow.com/a/41953265/578411
Console.ReadLine();